开发者

Android Creating Array of widgets in the XML and reading in activity

In my project i have several TextBoxes which i have to fill dynmicall开发者_开发技巧y. I have the values to be filled in a list, and i want to apply setText to the text boxes at the time of iterating list. Is this possible to have the name of widget as array type like textbox[1], textbox[2]....... Here in the xml it do not give any error but in the activity class while reading it gives error,

findViewById(R.id.textbox[1]    //textbox cannot be resolved or is not a field. 

Is there any other way of manipulating this? Thanks.


You would try using reflection:


for(int i = 0; condition;i++){
    try {
        int id = (Integer) R.id.class.getField("textbox"+i).get(null);
        TextView textView = (TextView) findViewById(id);
        textView.setText("i th text from your list");
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


well you can make your own array of textboxs...

    ArrayList<TextBox> textbox = new new ArrayList<TextBox>();
    textbox.add((TextBox)findViewById(R.id.textbox1);  
    textbox.add((TextBox)findViewById(R.id.textbox2); 

then use it like: textbox[1]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜