【问题标题】:Android Creating Array of widgets in the XML and reading in activityAndroid 在 XML 中创建小部件数组并读取活动
【发布时间】:2011-09-16 07:24:26
【问题描述】:

在我的项目中,我有几个必须动态填充的文本框。我有要填写在列表中的值,并且我想在迭代列表时将 setText 应用于文本框。 这是否可以将小部件的名称作为数组类型,如 textbox[1]、textbox[2]....... 在 xml 中它不会给出任何错误,但在读取它时在活动类中会给出错误,

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

还有其他方法可以处理吗?谢谢。

【问题讨论】:

    标签: android android-layout android-activity android-emulator android-widget


    【解决方案1】:

    你会尝试使用反射:

    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】:

      你可以制作自己的文本框数组...

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

      然后像这样使用它:textbox[1]

      【讨论】:

      • add 方法不适用于 TextView。请详细说明代码。谢谢。
      • 苏达尔的回答可能会更好:)
      • 是的,Amitay,问题已通过 sundar 的帖子解决。感谢您的帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多