dimanche 26 avril 2015

Calling text from XML to the manually created object in Activity's method in Android


I am trying to create a submit and clear button by a for loop in the onCreate() method by using programming instead of XML layout, and I have defined the label text of the button from the string.xml and assigned it. However, the application has been stopped when I run it.

I have tried to hide the button label setting and it can be work as useal(2 button displayed on the apps without error), thus I am wondering if it is not possible to call string label directly from XML?? or I missed something to do so. Pls give me some comment.

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TableLayout tableLayout = new TableLayout(this);
    tableLayout.setOrientation(TableLayout.VERTICAL);
    setContentView(tableLayout);

    Button[] buttons = new Button[2];

    //button label
    buttons[0].setText(R.string.label_calc);
    buttons[1].setText(R.string.label_clear);

    for(int i=0; i<2; i++) {
        buttons[i] = new Button(this);
        tableLayout.addView(buttons[i]);
    }

}

Here is the label setting in string.xml:

<!-- button label-->
<string name="label_calc">Calc</string>
<string name="label_clear">Clear</string>


Aucun commentaire:

Enregistrer un commentaire