两个具有相同ID的视图

tez*_*tez 25 android

R.id.id_name在扩充XML之后,android如何使用它来查找视图?

1.假设我有两个XML,一个按钮,每个都有相同的ID.

我已经给他们充气并把它们变成了意见

3.在R.id类中,只int为这两个按钮创建一个.

android如何区分具有相同id的这些按钮使用相同的资源名称(R.id.id_name).

Rob*_*ham 34

该ID不是唯一的参考.

但是,实际上,您可以使用父视图进行区分.

如果我们认为'this'是一个Activity,使用包含按钮的布局进行设置,那么:

Button button = (Button) this.findViewById( R.id.id_name );
Run Code Online (Sandbox Code Playgroud)

将返回它在布局中找到的第一个(我认为 - 不确定实际行为是否已定义).

但是,您可能会调用findViewById一些父视图,该视图仅包含一个具有该ID的此类实例.

LinearLayout okParent = (LinearLayout) this.findViewById( R.id.okLayout );
LinearLayout cancelParent = (LinearLayout) this.findViewById( R.id.cancelLayout );

Button okButton = (Button) okParent.findViewById( R.id.id_name );
Button cancelButton = (Button) cancelParent.findViewById( R.id.id_name );
Run Code Online (Sandbox Code Playgroud)

从概念上讲,这是一种基于路径的查找.您应该小心设计布局,以便这样做.


sle*_*ica 15

Android采取了简单的方法:ID不是应用程序范围内唯一的,但布局范围内唯一.

R.id.foo具有fooid 的控件的两个不同布局中,值是相同的.由于他们没有竞争独特性,因此无关紧要.

  • 光滑!android采取的非常好的方法 (2认同)

Pio*_*cki 6

它知道它View应该使用哪个,因为它在当前设置为内容视图(或被夸大)的XML文件中查找View具体id内容.