【问题标题】:How to reference R.id s with indices? [duplicate]如何使用索引引用 R.id ? [复制]
【发布时间】:2014-06-29 19:16:52
【问题描述】:

我的 activity.java 文件中有这个。

    text[0] = (EditText) findViewById(R.id.editText2);
    text[1] = (EditText) findViewById(R.id.editText3);
    text[2] = (EditText) findViewById(R.id.editText4);
    text[3] = (EditText) findViewById(R.id.editText5);
    text[4] = (EditText) findViewById(R.id.editText6);
    text[5] = (EditText) findViewById(R.id.editText7);
    text[6] = (EditText) findViewById(R.id.editText8);
    text[7] = (EditText) findViewById(R.id.editText9);

如何使用 for 循环编写它。

 for(int i=o;i<8;i++)
 text[i] = (EditText) findViewById(R.id.<what here>);

如何在这里引用带有索引的edittext?

【问题讨论】:

  • 不要以为可以直接做,只要把必要的id放到一个数组里循环遍历就好了。

标签: android for-loop android-edittext


【解决方案1】:

您可以使用getIdentifier() 实现此目的

for(int i=0; i<8; i++) {
   for(int j=0; j<8; j++) {
    String editTextID = "btn" + i + "-" + j;
    int resID = getResources().getIdentifier(editTextID
    ,"id", "com.example.yourpackagename");
    buttons[i][j] = ((EditTextID) findViewById(resID));
   }
}

【讨论】:

    【解决方案2】:

    您可以为此使用常量数组。

    // in your class 
    private static final int[] TEXT_IDS = { R.id.editText2, R.id.editText3, ... , R.id.editText9};
    
    //initializing
    for(int i = o; i < TEXT_IDS.length; i++)
        text[i] = (EditText) findViewById(TEXT_IDS[i]);
    

    【讨论】:

      【解决方案3】:

      您可以尝试类似下面的答案,该答案逐字取自here

      import java.lang.reflect.Field;
      /* ... */
      
      for (int i = 1; i < 16; i++) {
          int id = R.id.class.getField("s" + i).getInt(0);
          tv[i] = (TextView)findViewById(id);
          tv[i].setTypeface(face);
          tv[i].setClickable(true);
          tv[i].setOnClickListener(clickListener);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-07
        • 1970-01-01
        • 1970-01-01
        • 2018-04-02
        相关资源
        最近更新 更多