Android: How to place a button with text with multi-line text?

I want to put a button at the end of a textview paragraph, for example, like the Go button when a user clicks on it and the application goes to another page.

eg:

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 the above example [Go->], a tiny button that should fit exactly at the end of a line.

how can i do this at runtime?

+4
source share
2 answers

You can use spaces for this.

Suppose you have 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);

, ( TextView, ), .

+5

, html

HTML img ,

  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));

.

+1

Source: https://habr.com/ru/post/1537964/


All Articles