setEditText没有ID

问题描述 投票:-1回答:4

我想打电话给这是我的矩阵的计算位置而得名,我的意思是,建设的EditText的ID与串并随后将其设置一个特定的EditText。现在我需要设置editText01文本布局,通常我会这样设置:

EditText et = (EditText) findViewById(R.id.editText01);

editText01.setText("WHATEVER I NEED");

但是,我不能由ID名字,因为我要访问一个特定的基础上,该行访问,列,因此它必须是这样的:

String row = "0"; // row index converted to string, for example

String column = "1"; // column index converted to string, for example

String string = "editText" + row + column; // string should be editText01

string.setText("WHATEVER I NEED"); //WRONG LINE
android
4个回答
0
投票

使用字符串来调用特定的编辑文本使用此代码来创建ID

  String viewID="editText" + row + column; // string should be editText01
     //id for view
    int resID= getResources().getIdentifier(viewID,"id", getPackageName()); 
    EditText edit= (EditText) findViewById(resID);
    edit.setText("WHATEVER I NEED");

在这段代码中使用字符串创建EDITTEXT ID


1
投票

解决方法1:在你的情况,你可以检查R.java类,并得到EDITTEXT的ID。但我建议的解决方案2,以避免在代码中使用反射。

下面是使用反射的代码。

private int findIdByName(String nameOfId) {
   try {
        Class IdFolder = Class.forName(context.getPackageName()+".R$id");
        Field field = IdFolder.getField(nameOfId);
        return (int) field.get(null);
   } catch (ClassNotFoundException e) {
         Log.e(TAG, "can not find R.java class");
         e.printStackTrace();
   } catch (NoSuchFieldException e) {
         Log.e(TAG, "the field of resource not defined");
         e.printStackTrace();
   } catch (IllegalAccessException e) {
         Log.e(TAG, "can not get static field in R");
         e.printStackTrace();
   } catch (ClassCastException e) {
         Log.e(TAG, "the value of field is not integer");
         e.printStackTrace();
   }
   return 0;
}

String idName = "editText" + row + column; // string should be editText01
int id = findIdByName(idName);
if (id != 0)
   EditText editText01 = findViewById(id);

方案2:您必须在EditText创建for并设置一个ID为每一个。然后把每个EditText到一个数组列表。

所以,你要访问你在数组列表中的所有对象的EditText每次。对于更多的理解我说的话请看下图:

List<EditText> list = new ArrayList();
for (int i=0; i<100; i++) {
   EditText editText = new EditText(context);
   editText.setId("editText" + row + column);
   list.add(editText);
}

当你想要一个EditText你可以调用这个方法:

private EditText findEditText(String id) {
   for (EditText editText: list)
      if (editText.getId().equals(id)
         return editText;

   return null;
}

也不要忘了添加的每个的EditText在视图中。例如,你可以把一个的LinearLayout在布局后创建的每个EditText添加到LinearLayout中。这样的事情摆在for

LinearLayout linear = findViewById(R.id.linear);
for (int i=0; i<100; i++) {
//...
   linear.addView(editText)
/...
}

如果你不明白我说的,可随时把评论和提问。


0
投票

你应该为所有编辑文本的标签,如

EditText et = new EditText(this);
et.setTag(<some tag >);

然后利用到findViewByTag API来检索编辑文本

   EditText et = (EditText)findViewByTag(<tag name>);

0
投票

您可以使用getIdentifier()

int id = context.getResources().getIdentifier("editText" + row + column, "id", context.getPackageName());
EditText et = (EditText) findViewById(id);
et.setText("WHATEVER I NEED");

您可以在活动课中省略context

© www.soinside.com 2019 - 2024. All rights reserved.