与 Android 中的 setId() 方法混淆 [英] Confusion with setId() method in Android

查看:24
本文介绍了与 Android 中的 setId() 方法混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对 setId() 方法的描述.

<块引用>

void android.view.View.setId(int id)

public void setId(int id)

因为:API 级别 1

设置此视图的标识符.标识符不必是在此视图的层次结构中是独一无二的.标识符应该是正数号.

我的问题是,尽管我们在 XML 文件中分配了唯一的 ID,但为什么标识符在此视图的层次结构中不必是唯一的?

解决方案

我的问题是,尽管我们在 xml 文件中分配了 unigue id,但为什么标识符在此视图的层次结构中不必是唯一的..?

android:id 在 XML 文件中也不必是唯一的,尽管这是您编写它的典型方式.

要了解为什么小部件 ID 不需要唯一,请考虑 ListView.假设我们有一个 8 行的 ListView.这些行中的每一行都是通过扩充布局 XML 资源(例如,android.R.layout.simple_list_item_1)来创建的.这些膨胀的每一行都是 ListView 的子元素.然而,由于这些行中的每一行都来自相同的布局资源,因此每一行的小部件都具有与所有其他行相同的 ID.

这通常不是问题.它确实导致了 Android 开发的一个基本规则:总是在某些东西上调用 findViewById(),这将为您寻找的小部件提供独特的结果.在这种情况下,我不想在 ListViewActivity 上调用 findViewById() 来查找其中一行中的小部件,因为会有 8 个小部件都具有相同的 ID,而且我不知道我会返回哪一行的小部件.相反,我需要在 row 上调用 findViewById(),以从该特定行获取特定小部件.

This is the description given for the setId() method.

void  android.view.View.setId(int id)

public void setId (int id)

Since: API Level 1

Sets the identifier for this view. The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

My question is, why does the identifier not have to be unique in this view's hierarchy though we assign unique ids in an XML file?

解决方案

My question is, why does the identifier not have to be unique in this view's hierarchy though we assign unigue id in xml file..?

The android:id does not have to be unique in the XML file, either, though that is the way you write it, typically.

To understand why a widget ID does not need to be unique, consider the ListView. Let's say that we have a ListView with 8 rows. Each of those rows is created by inflating a layout XML resource (e.g., android.R.layout.simple_list_item_1). Each of those inflated rows are children of the ListView. Yet, since each of those rows is inflated from the same layout resource, each row's widgets have the same IDs as all the other rows.

This is not generally a problem. It does lead to one cardinal rule of Android development: always call findViewById() on something that will give you a unique result for the widget you seek. In this case, I do not want to call findViewById() on the ListView or the Activity to find a widget inside of one of the rows, as there will be 8 widgets all with the same ID, and I do not know which row's widget I will get back. Instead, I need to call findViewById() on the row, to get the particular widget from that specific row.

这篇关于与 Android 中的 setId() 方法混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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