Android的R.id需要独一无二吗?

时间:2015-10-25 06:29:43

标签: android r.id

Android的R.id是否必须是独一无二的(因为我到目前为止一直保留它们)?

或者可以在不同的视图中重用R.id吗?

4 个答案:

答案 0 :(得分:5)

ID用于查找视图层次结构中的视图。 Android使用depth-first search algorithm - 意味着它会查看一个树分支的最底部,然后查看另一个树分支等。如果您有两个具有相同ID的视图,则算法将找到第一个视图并停止进一步搜索。

对ID的唯一性没有严格的要求。例如,当您有一个列表视图时,该列表的每个项目将使用相同的布局进行膨胀,并且在大多数情况下将具有相同的共享ID,这是完全正常的。

记住这一点,如果您有两个(或更多)视图共享相同的ID,您应该帮助Android选择正确的视图。为此,您首先需要搜索该视图的正确父级,然后搜索视图本身。

例如,如果在两个不同的片段中有两个具有相同ID的视图,则应首先搜索片段容器视图,然后搜索该容器内具有共享ID的视图。

答案 1 :(得分:3)

是的,可以在不同的布局中使用相同的ID。您可以在此处找到更多信息:http://developer.android.com/guide/topics/ui/declaring-layout.html

  

任何View对象都可以有一个与之关联的整数ID,以唯一标识树中的View。编译应用程序时,此ID被引用为整数,但ID通常在布局XML文件中作为字符串在id属性中指定。


  

在相对布局中,兄弟视图可以相对于另一个兄弟视图定义其布局,该视图由唯一ID引用。

     

ID在整个树中不一定是唯一的,但它在您正在搜索的树的部分(通常可能是整棵树)中应该是唯一的,因此在可能的情况下它最好是完全唯一的)。

答案 2 :(得分:2)

可以使用不同布局的相同ID。

例如:

<强> a.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a);

<强> b.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.b);

<强> A.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/id_rel"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp"
 >

<强> B.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/id_rel"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp"
 >

但是在一个布局中使用相同的id会导致异常

答案 3 :(得分:0)

对于大多数情况,您可以在不同的布局中重复使用id。但是你应该知道使用,标签或使用自定义复合视图以及添加到当前视图的列表项或片段将一个布局包含到另一个布局中的可能性。