【问题标题】:Reference control using string instead ID使用字符串而不是 ID 引用控件
【发布时间】:2011-02-09 18:32:32
【问题描述】:

引用android控件的典型方式是这样的:

TextView tv = (TextView)findViewById(R.id.tv);

其中 R.id.tv 是引用我的 xml 控件的整数。

问题是我想使用字符串“R.id.tv”进行参考。这可能吗?

假设我有多个控件:

tv1,
tv2,
tv3,
tv4,
tv5,

我如何将它放入某种循环并通过控件进行交互。我想我会使用循环计数器来引用不同的控件。那要怎么做?谢谢。

【问题讨论】:

    标签: android reference controls


    【解决方案1】:

    一种方法是将 id 放入数组中并通过下标引用。

    int[] ids = { R.id.tv1, R.id.tv2 /* etc. */ };
    for (int i = 0; i < ids.length; ++i) {
        TextView tv = (TextView)findViewById(ids[i]);
    }
    

    【讨论】:

      【解决方案2】:

      尝试下一个

      private int getIdResourceByName(String aString)
      {
        String packageName = "com.myProject.myPackage"; // set your package name here
        int resId = getResources().getIdentifier(aString, "id", packageName);
        return resId;
      }
      

      ...

        for (int i = 1; i<=5; i++) {
            TextView tv = (TextView) findViewById(getIdResourceByName("tv" + Integer.toString(i)));
            ...
           }
      

      【讨论】:

        【解决方案3】:

        【讨论】:

        • 谢谢。我正在查看 getIdentifier 但我不太确定如何正确使用它。您链接的示例准确地说明了我想要实现的目标。
        【解决方案4】:

        我不明白您为什么要这样做,它非常丑陋、效率低下,并且可能导致维护问题和错误。

        为什么不使用集合(例如 ArrayList)来存储对所有控件的引用?

        【讨论】:

          猜你喜欢
          • 2019-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-09-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多