Android:查找动态创建的视图的ID [英] Android: Find an ID of dynamically created view

查看:148
本文介绍了Android:查找动态创建的视图的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下问题:

在Android Studio中,当单击ExerciseButton时,我会动态生成EditText:

In Android Studio I generate en EditText dynamically when an ExerciseButton is clicked:

public void exerciseButtonClick(View view) {
  EditText exercise = new EditText(this);
  exercise.setId(exerciseId);
  exerciseId++;
}

稍后在代码中,我想通过ID引用我所有的EditText.我正在尝试类似的操作,但这不起作用:

Later in the code I would like to refer to all my EditText's via ID. I'm trying something like this but this is not working:

for (int i = 1; i < exerciseId; i++) {
                EditText currentEditText = (EditText) findViewById(i);
                // further instructions on that EditText
}

错误当然在这里:findViewById(i),显示预期的资源类型为id .我该如何解决这个问题?

The error is of course here: findViewById(i), showing Expected resource type to be on of id. How can I solve this problem?

推荐答案

您需要确保ID与Android生成的ID不冲突.另外,您需要确保将视图添加到活动视图层次结构中,否则将永远找不到它们.

You need to make sure the ID doesn't clash with the Android generated id's. Also, you need to make sure you add the views to the activity view hierarchy, otherwise they will never be found.

在您的情况下,我可能会尝试以下操作之一

In your scenario, i would probably try one of the following things

1)如果您仍想使用整数id,请使用此方法生成有效的非冲突ID

1) If you still want to use integer id's, then use this method to generate a valid non-clashing id

https://developer.android.com/reference/android/view/View.html#generateViewId

2)将tag设置为视图,然后按tag进行检索.标签可以是任何对象.

2) Set tag to the view, and retrieve by tag. Tag can be any object.

public void exerciseButtonClick(View view) {
  EditText exercise = new EditText(this);
  exercise.setTag("exercise-" + excersiceId);
  excersiceId++;
}


EditText exercise = (EditText)findViewByTag("exercise-" + someId );

3)保留一个局部变量,保留对创建的EditText(或对创建的EditText数组的引用)

3) Keep a local variable, holding the reference to the created EditText (or to the created array of EditTexts)

private EditText exercise;

public void exerciseButtonClick(View view) {
  exercise = new EditText(this);
  excersiceId++;
}

这篇关于Android:查找动态创建的视图的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆