Android widget: How to change the text of a button

前端 未结 7 1509
野性不改
野性不改 2020-12-13 06:31

How can I change the text of an Android button widget within code and not the XML file?

7条回答
  •  醉梦人生
    2020-12-13 06:51

    This may be off topic, but for those who are struggling on how to exactly change also the font of the button text (that was my case and Skatephone's answer helped me) here's how I did it (if you made buttons ind design mode):

    First we need to have the button's string name "converted" (it's a foul way to explain, but straightforward) into java from the xml, and so we paste the aforementioned code into our MainActivity.java

    IMPORTANT! place the code under the OnCreate method!

    import android.widget.RemoteViews;
    
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.my_layout);
    remoteViews.setTextViewText(R.id.Counter, "Set button text here");
    

    Keep in mind:

    my_layout has to be substituted with the xml file where your buttons are

    Counter has to be substituted with the id name of your button ("@+id/ButtonName")

    if you want to change the button text just insert the text in place of "Set button text here"

    here comes the part where you change the font:

    Now that you "converted" from xml to java, you can set a Typeface method for TextView. Paste the following code exactly under the previous one just described above

    TextView txt = (TextView) findViewById(R.id.text_your_text_view_id);
            Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MyFontName.ttf");
            txt.setTypeface(font);
    

    where in place of text_your_text_view_id you put your button's id name (like as previous code) and in place of MyFontName.ttf you put your desired font

    WARNING! This assumes you already put your desired font into the assets/font folder. e.g. assets/fonts/MyFontName.ttf

提交回复
热议问题