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

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

问题描述

我有两个不同的布局用于两个不同的活动.每个布局中都有一个具有相同 id 的按钮:@+id/btnOK".当我以编程方式为这些按钮之一设置属性时,我得到一个 NullPointerException.但是当我更改其中一个 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.

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

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

推荐答案

关于Duplicate Ids in layouts"话题,摘自android 开发者

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

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

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).

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

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

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

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