如何在不同的布局中使用重复的ID? [英] How can I use duplicate IDs in different layouts?

查看:209
本文介绍了如何在不同的布局中使用重复的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于两个不同的活动,我有两种不同的布局。每个布局中都有一个按钮,具有相同的ID:@ + id / btnOK。当我以编程方式为这些按钮之一设置一个属性时,我得到一个 NullPointerException 。但是,当我更改其中一个ids时,一切都可以。



这是真的吗,我们不能在android中的不同布局中有重复的ID?

$ b $在
解决方案

/declaring-layout.html#idrel =noreferrer> android开发人员



创建RelativeLayout时,定义视图对象的ID很重要。在相对布局中,兄弟姐妹视图可以相对于另一个兄弟视图定义其布局,该视图由唯一ID引用。



整个树中的ID不一定是独一无二的,但它在你正在搜索的树的部分中应该是唯一的(通常可能是整个树),所以最好是尽可能完全独特。 / em>



这意味着不同的布局可能会声明相同的ID,这不是最佳做法。


I have two different layouts for two different Activities. There is a button in each of these layouts with the same id: "@+id/btnOK". When I set a property for one of these buttons programmatically, I get a NullPointerException. But when I change one of ids, everything is okay.

Is it really true that we cannot have duplicate IDs in different layouts in android?

解决方案

On the "Duplicate Ids in layouts" topic, extracted from android developers

Defining IDs for view objects is important when creating a RelativeLayout. In a relative layout, sibling views can define their layout relative to another sibling view, which is referenced by the unique ID.

An ID need not be unique throughout the entire tree, but it should be unique within the part of the tree you are searching (which may often be the entire tree, so it's best to be completely unique when possible).

Which means different layouts may declare identical IDs, tho it's not a best practice.

这篇关于如何在不同的布局中使用重复的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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