14

I have a button in my application. the text in the button goes as "Type: Location" something like that.

I'm wondering whether its possible to change the text on the button as "Type: Location"

i.e Bold the text partially on the button??

Thanks for yoru time in advance.

6 Answers 6

33

we have a more better choice like this :android:textStyle="bold" android api support bold

2
  • 1
    this will bold the whole text in the button :(
    – Jaya Mayu
    Sep 2, 2011 at 10:54
  • I ask my master ,he say that Html.fromHtml is better and more easlier control.
    – Yang Li
    Sep 2, 2011 at 10:54
24

Simply put your string in strings.xml and change it like this,

 <string name="hello"><b>Hello</b> World, fh!</string>

and set this text to your button like this

<Button
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textAllCaps="false"
    android:text="@string/hello"
    />

Sometimes the above approach will not be helpful when you might have to use Dynamic Text. So at that case SpannableString comes into action.

  String tempString="Copyright";
  Button button=(Button)findViewById(R.id.button);
  SpannableString spanString = new SpannableString(tempString);
  spanString.setSpan(new StyleSpan(Typeface.BOLD), 0, spanString.length(), 0);
  button.setText(spanString);
1
  • 4
    Don't forget add android:textAllCaps="false" (it doesn't work without that thing) Nov 9, 2017 at 13:12
4

You can set it using Html.fromHtml() and give as a string, a string resource with HTML elements. Hope this helps!

3

Using spans:

SpannableStringBuilder builder = new SpannableStringBuilder("Type: your type here!");
StyleSpan boldStyle = new StyleSpan(Typeface.BOLD);
builder.setSpan(boldStyle, 0, 5, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
((Button) findViewById(R.id.button)).setText(builder);
2

You can use basic markup directory in strings, e.g.

"<b>Type</b>: Location"

See Styling with HTML markup

1

If want to set text programmatically then use this method

Button

First you have to set button's property in XML

android:textAllCaps="false" // very important without this property might be it won't show effect

public SpannableString setSpanableString(String textString, int start, int end){

    SpannableString spanString = new SpannableString(textString);
    spanString.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0);

    return spanString;
}


Button btn; // get your button reference here

String text = "Hi, Dharmbir";
btn.setText(setSpanableString(text, 4, text.length));// set here your index

TextView

TextView tv; // get your TextView reference here

String text = "Hi, Dharmbir";
tv.setText(setSpanableString(text, 4, text.length));

Output

Hi, Dharmbir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.