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

≯℡__Kan透↙ 提交于 2019-12-12 01:27:12

问题


In my project i have several TextBoxes which i have to fill dynmically. 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.


回答1:


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




回答2:


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]



来源:https://stackoverflow.com/questions/7441419/android-creating-array-of-widgets-in-the-xml-and-reading-in-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!