Cómo hacer clic en la parte de la vista de texto

Tengo el texto ” Android es una stack de software “. En este texto quiero establecer que se pueda hacer clic en el texto de ” stack “. en el sentido de que si hace clic en eso se redireccionará a una nueva actividad (no en el navegador).

Lo intenté pero no lo estoy entendiendo.

android.text.style.ClickableSpan puede resolver su problema.

 SpannableString ss = new SpannableString("Android is a Software stack"); ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View textView) { startActivity(new Intent(MyActivity.this, NextActivity.class)); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }; ss.setSpan(clickableSpan, 22, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); TextView textView = (TextView) findViewById(R.id.hello); textView.setText(ss); textView.setMovementMethod(LinkMovementMethod.getInstance()); textView.setHighlightColor(Color.TRANSPARENT); 

// En XML: TextView: android: textColorLink = “@ drawable / your_selector”

Mi función para hacer múltiples enlaces dentro de TextView

 public void makeLinks(TextView textView, String[] links, ClickableSpan[] clickableSpans) { SpannableString spannableString = new SpannableString(textView.getText()); for (int i = 0; i < links.length; i++) { ClickableSpan clickableSpan = clickableSpans[i]; String link = links[i]; int startIndexOfLink = textView.getText().toString().indexOf(link); spannableString.setSpan(clickableSpan, startIndexOfLink, startIndexOfLink + link.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } textView.setHighlightColor( Color.TRANSPARENT); // prevent TextView change background when highlight textView.setMovementMethod(LinkMovementMethod.getInstance()); textView.setText(spannableString, TextView.BufferType.SPANNABLE); } 

UTILIZANDO

 textView.setLinkTextColor(Color.BLUE); // default link color for clickable span, we can also set it in xml by android:textColorLink="" ClickableSpan normalLinkClickSpan = new ClickableSpan() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "Normal Link", Toast.LENGTH_SHORT).show(); } }; ClickableSpan noUnderLineClickSpan = new ClickableSpan() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "NoUnderLine Link", Toast.LENGTH_SHORT) .show(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); ds.setColor(Color.MAGENTA); // specific color for this link } }; ClickableSpan highlightClickSpan = new ClickableSpan() { @Override public void onClick(View view) { Toast.makeText(getApplicationContext(), "Highlight Link", Toast.LENGTH_SHORT) .show(); view.invalidate(); // need put invalidate here to make text change to GREEN after clicked } @Override public void updateDrawState(TextPaint ds) { ds.setUnderlineText(false); if (textView.isPressed() && textView.getSelectionStart() != -1 && textView.getText() .toString() .substring(textView.getSelectionStart(), textView.getSelectionEnd()) .equals("Highlight Link")) { ds.setColor(Color.RED); // need put invalidate here to make text change to RED when pressed on Highlight Link textView.invalidate(); } else { ds.setColor(Color.GREEN); } // dont put invalidate here because if you put invalidate here `updateDrawState` will called forever } }; makeLinks(textView, new String[] { "Normal Link", "NoUnderLine Link", "Highlight Link" }, new ClickableSpan[] { normalLinkClickSpan, noUnderLineClickSpan, highlightClickSpan }); 

XML

  

enter image description here

Puede usar ClickableSpan como se describe en esta publicación

Código de muestra:

 TextView myTextView = new TextView(this); String myString = "Some text [clickable]"; int i1 = myString.indexOf("["); int i2 = myString.indexOf("]"); myTextView.setMovementMethod(LinkMovementMethod.getInstance()); myTextView.setText(myString, BufferType.SPANNABLE); Spannable mySpannable = (Spannable)myTextView.getText(); ClickableSpan myClickableSpan = new ClickableSpan() { @Override public void onClick(View widget) { /* do something */ } }; mySpannable.setSpan(myClickableSpan, i1, i2 + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

Referencia

Puedes usar código de muestra. Desea conocer detalles sobre ClickableSpan. Por favor revisa esta documentacion

  SpannableString myString = new SpannableString("This is example"); ClickableSpan clickableSpan = new ClickableSpan() { @Override public void onClick(View textView) { ToastUtil.show(getContext(),"Clicked Smile "); } }; //For Click myString.setSpan(clickableSpan,startIndex,lastIndex,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) //For UnderLine myString.setSpan(new UnderlineSpan(),startIndex,lastIndex,0); //For Bold myString.setSpan(new StyleSpan(Typeface.BOLD),startIndex,lastIndex,0); //Finally you can set to textView. TextView textView = (TextView) findViewById(R.id.txtSpan); textView.setText(myString); textView.setMovementMethod(LinkMovementMethod.getInstance()); 

Hice este método de ayuda en caso de que alguien necesite la posición inicial y final de una Cadena.

 public static TextView createLink(TextView targetTextView, String completeString, String partToClick, ClickableSpan clickableAction) { SpannableString spannableString = new SpannableString(completeString); // make sure the String is exist, if it doesn't exist // it will throw IndexOutOfBoundException int startPosition = completeString.indexOf(partToClick); int endPosition = completeString.lastIndexOf(partToClick) + partToClick.length(); spannableString.setSpan(clickableAction, startPosition, endPosition, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); targetTextView.setText(spannableString); targetTextView.setMovementMethod(LinkMovementMethod.getInstance()); return targetTextView; } 

Y así es como lo usas

 private void initSignUp() { String completeString = "New to Reddit? Sign up here."; String partToClick = "Sign up"; ClickableTextUtil .createLink(signUpEditText, completeString, partToClick, new ClickableSpan() { @Override public void onClick(View widget) { // your action Toast.makeText(activity, "Start Sign up activity", Toast.LENGTH_SHORT).show(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); // this is where you set link color, underline, typeface etc. int linkColor = ContextCompat.getColor(activity, R.color.blumine); ds.setColor(linkColor); ds.setUnderlineText(false); } }); } 
  t= (TextView) findViewById(R.id.PP1); t.setText(Html.fromHtml("" + "This is cliclable text ")); t.setMovementMethod(LinkMovementMethod.getInstance()); 

Versión de Kotlin de la respuesta de Phan Van Linh.

Tenga en cuenta que tiene algunas modificaciones menores.

 fun makeLinks(textView: TextView, links: Array, clickableSpans: Array) { val spannableString = SpannableString(textView.text) for (i in links.indices) { val clickableSpan = clickableSpans[i] val link = links[i] val startIndexOfLink = textView.text.indexOf(link) spannableString.setSpan(clickableSpan, startIndexOfLink, startIndexOfLink + link.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } textView.movementMethod = LinkMovementMethod.getInstance() textView.setText(spannableString, TextView.BufferType.SPANNABLE) } fun setupClickableTextView() { val termsOfServicesClick = object : ClickableSpan() { override fun onClick(p0: View?) { Toast.makeText(applicationContext, "ToS clicked", Toast.LENGTH_SHORT).show() } } val privacyPolicyClick = object : ClickableSpan() { override fun onClick(p0: View?) { Toast.makeText(applicationContext, "PP clicked", Toast.LENGTH_SHORT).show() } } makeLinks(termsTextView, arrayOf("terms", "privacy policy"), arrayOf(termsOfServicesClick, privacyPolicyClick)) } 

Para negrita,

 mySpannable.setSpan(new StyleSpan(Typeface.BOLD),termStart,termStop,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

Puede este método para establecer el valor cliqueable

 public void setClickableString(String clickableValue, String wholeValue, TextView yourTextView){ String value = wholeValue; SpannableString spannableString = new SpannableString(value); int startIndex = value.indexOf(clickableValue); int endIndex = startIndex + clickableValue.length(); spannableString.setSpan(new ClickableSpan() { @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); // < -- this will remove automatic underline in set span } @Override public void onClick(View widget) { // do what you want with clickable value } }, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); yourTextView.setText(spannableString); yourTextView.setMovementMethod(LinkMovementMethod.getInstance()); // <-- important, onClick in ClickableSpan won't work without this } 

Esta es la forma de usarlo:

 TextView myTextView = findViewById(R.id.myTextView); setClickableString("stack", "Android is a Software stack", myTextView); 

Aquí hay un método de Kotlin para hacer que partes de un TextView hacer clic:

 private fun makeTextLink(textView: TextView, str: String, underlined: Boolean, color: Int?, action: (() -> Unit)? = null) { val spannableString = SpannableString(textView.text) val textColor = color ?: textView.currentTextColor val clickableSpan = object : ClickableSpan() { override fun onClick(textView: View) { action?.invoke() } override fun updateDrawState(drawState: TextPaint) { super.updateDrawState(drawState) drawState.isUnderlineText = underlined drawState.color = textColor } } val index = spannableString.indexOf(str) spannableString.setSpan(clickableSpan, index, index + str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) textView.text = spannableString textView.movementMethod = LinkMovementMethod.getInstance() textView.highlightColor = Color.TRANSPARENT } 

Se puede llamar varias veces para crear varios enlaces dentro de un TextView:

 makeTextLink(myTextView, str, false, Color.RED, action = { Log.d("onClick", "link") }) makeTextLink(myTextView, str1, true, null, action = { Log.d("onClick", "link1") })