Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 483
SadeghAlavizadeh Avatar asked Apr 24 '14 21:04

SadeghAlavizadeh


2 Answers

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.

like image 94
Kevin Coppock Avatar answered Nov 17 '22 15:11

Kevin Coppock


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.

like image 1
Libin Avatar answered Nov 17 '22 16:11

Libin