gpt4 book ai didi

android - 具有相同 ID 的两个 View

转载 作者:IT老高 更新时间:2023-10-28 22:20:24 24 4
gpt4 key购买 nike

android在inflating XML后如何使用R.id.id_name查找 View ?

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

2.我已经将它们膨胀并转换为 View

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

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

最佳答案

ID 不是唯一的引用。

但是,在实践中,您可以通过使用父 View 来区分。

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

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

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

但是,您可能要做的是在某些父 View 上调用 findViewById,该父 View 仅包含一个具有该 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 );

从概念上讲,这是一种基于路径的查找。你应该小心设计你的布局,这样才有可能。

关于android - 具有相同 ID 的两个 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14759056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com