安卓创建的XML控件数组和阅读活动数组、控件、XML

2023-09-12 06:05:12 作者:18.心已盲

在我的项目,我有几个文本框,我必须填写dynmically。我有值要填充的列表,和我想申请的setText到文本框在迭代列表的时间。 这是可能有插件的名称作为数组类型,如TextBox [1],文本框[2]。......在这里,在XML它不给任何错误,但在活动课,而阅读提示错误,

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.

推荐答案

您会尝试使用反射:



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

 
精彩推荐
图片推荐