Android: How to place a button end of a textview with multiline text?

android, layout, textview

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.

Problem

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?

Original source