Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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

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

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

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

See Styling with HTML markup

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

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