7

how do I use html in an android widget Button?

Nikhil
  • 16,194
  • 20
  • 64
  • 81
user121196
  • 30,032
  • 57
  • 148
  • 198

3 Answers3

8

You should be able to use Html.fromHtml() to convert raw HTML into a Spanned object that you can use in a setText() call on your button. As the Html documentation states, "Not all HTML tags are supported".

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • is there a way to do it without using Java code? I have static text encoded in a resource file: – user121196 Jul 14 '09 at 22:16
  • You should be able to use the same method call that @commonsware.com used, and just get the string from the resource file. Context.getString(R.id.x) should be it – Andrew Burgess Jul 15 '09 at 04:53
3

Mark's answer is spot on, as usual. Here is a more complete example for reference though (this is a confusing part of the docs). (And, yes, I know this example isn't using a Button, but this is the one I had handy, and it's the same idea.)

String needs to be a resource:

 <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <string name="mystring">    
        You can use regular text, and escaped HTML markup
        &lt;br /&gt;&lt;br /&gt;
        A simple BOLD example &lt;b&gt;StackOverflow&lt;/b&gt;.
    </string>
    </resources>

Then get the resource and use Html.fromHtml() (if you are using an EditText, you also need to make sure the buffer is set to SPANNABLE):

 public class MyActivity extends Activity {
    TextView myTextView;

       @Override
       public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.about);     

          myTextView = (TextView) this.findViewById(R.id.mytextview);
          myTextView.setText(Html.fromHtml(getResources().getString(R.string.mystring)),
                             TextView.BufferType.SPANNABLE);
       }  
       ...

Lastly, note that all HTML doesn't work, of course. So depending on your requirements, this might not be entirely useful. Also see this issue if you try to use a link (anchor tag) and you want it to respond to being clicked. For simple stuff, see Linkify.

Matt
  • 74,352
  • 26
  • 153
  • 180
Charlie Collins
  • 8,806
  • 4
  • 32
  • 41
1

These two answers are also valid, you can also do it like this. I was trying to do something of the same nature and found out that my html along with CSS was not getting formatted correctly so I took the string and loaded it into a webview like this:

 WebView webview = (WebView) findViewById(R.id.MyWebview);
 String summary = "<html><body>You scored <b>192</b> points.</body></html>";
 webview.loadData(summary, "text/html", "utf-8");

and it recognized all the styles and formatted the html correctly. More from the android reference HERE

ninjasense
  • 13,756
  • 19
  • 75
  • 92