具有相同ID的两个视图 [英] two views with same id

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

问题描述

膨胀XML后,android如何使用R.id.id_name查找视图?

How does android use R.id.id_name to find views after inflating the XML?

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

1.Suppose I have two XML's with one button each with same id.

2.我夸大了它们并将它们转换为视图

2.I have inflated them and converted them into views

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

3.In R.id class only one int will be created for both the buttons.

android如何使用相同的Resource name(R.id.id_name)区分具有相同id的这些按钮.

How does android differentiate these buttons with same id Using same Resource name(R.id.id_name) .

推荐答案

该ID不是唯一的引用.

The ID is not a unique reference.

但是,实际上,您是通过使用父视图来区分的.

However, in practice, you differentiate by using the parent view.

如果我们认为这"是一项活动,请设置包含您的按钮的布局,然后:

If we consider that 'this' is an Activity, set up with a layout that contains your buttons, then:

Button button = (Button) this.findViewById( R.id.id_name );

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

will return the first one it finds in the layout (I think - not sure the actual behaviour is defined).

但是,您可以在只包含一个具有该ID的此类实例的某个父视图上调用findViewById.

However what you might do is call findViewById on some parent view that contains only one such instance with that 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 );

从概念上讲,这是一种基于路径的查找.您应该谨慎设计布局,以使这成为可能.

Conceptually, this is a sort of path based lookup. You should be careful to design your layouts such that this is possible.

这篇关于具有相同ID的两个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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