Question

I want to place a button at end of the textview paragraph, like as "Go" button that when user click on it the app going to another page.

for example:

if you have good endurance, 
for killing the monster you must 
going to section 2. [Go->]

-if you haven't good endurance, 
flee to section 3. [Go->]

in above example [Go->] is a tiny button that must placing exactly in end of line.

how I can do it in runtime?

Was it helpful?

Solution

You can use spans for this.

Let's assume you have a TextView called myText.

Drawable goButtonDrawable = getResources().getDrawable(R.drawable.go_button);

String text = "If you have good endurance, for killing the monster you must go to section 2. [GO]"
String replace = "[GO]";

final int index = text.indexOf(replace);
final int endIndex = index + replace.length();

final ImageSpan imageSpan = new ImageSpan(goButtonDrawable, ImageSpan.ALIGN_BASELINE);
final ClickableSpan clickSpan = new ClickableSpan() {
    @Override public void onClick(View clicked) {
        // Do your [GO] action
    }
};

SpannableString spannedText = new SpannableString(text);
spannedText.setSpan(imageSpan, index, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannedText.setSpan(clickSpan, index, endIndex , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

myText.setText(spannedText);

Obviously this could be better abstracted (you could just make a custom TextView that handles this internally), but that's the general idea.

OTHER TIPS

You can achieve this by setting the text as html

Append the HTML img tag to your text and set it to text view like this

  String htmlText = "Your multi line text <img src=\"ic_go_icon\">";

  textView.setText(Html.fromHtml(htmlText, new Html.ImageGetter() {

  @Override
  public Drawable getDrawable(String source) {
  int resourceId = getResources().getIdentifier(source, "drawable",getPackageName());
 Drawable drawable = getResources().getDrawable(resourceId);
 drawable.setBounds(0, 0,    drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        return drawable;
    }
}, null));

But handling the click will be for complete text view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top