为什么视图的 id 在包含的布局中相同?

Why id of the views is the same in included layouts?

我对布局及其 ID 的一些奇怪行为有疑问。

假设我有主布局,我通过将其包含在 xml 布局中使用了其他布局的 3 倍。

当我得到包含布局内的按钮 id 时,所有包含的布局都相同。这是正确的行为吗?我想在 OnClickListener 中使用它来区分点击的按钮。

layout_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <Button
        android:id="@+id/btnDoSomething"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Do something" />

[... some other views ...]

</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include android:id="@+id/layout1"
        layout="@layout/layout_row" />

    <include android:id="@+id/layout2"
        layout="@layout/layout_row" />

    <include android:id="@+id/layout3"
        layout="@layout/layout_row" />

    [... some other views ...]

</LinearLayout>

主要活动

import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info

class MainActivity : AppCompatActivity(), AnkoLogger {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        info("${layout1.btnDoSomething.id}")
        info("${layout2.btnDoSomething.id}")
        info("${layout3.btnDoSomething.id}")
        //it logs the same id three times!
    }
}

您已使用 include 语句将相同的 layout_row.xml 布局文件包含三次,只是更改了所包含布局的 ID。

它们是彼此的精确副本,因此 android:id="@+id/btnDoSomething" 条目 returns 每次都是相同的 ID - ID 在 strings.xml 中定义。

此行为是正确的,因为包含使用具有相同视图 ID 的相同布局。如果你想区分按钮点击你可以为每个按钮创建一个不同的OnClickListener

layout1.findViewById(R.id.btnDoSomething).setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View view) {
      // button of layout1 click
   }
});

layout2.findViewById(R.id.btnDoSomething).setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View view) {
      // button of layout2 click
   }
});

layout3.findViewById(R.id.btnDoSomething).setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View view) {
      // button of layout3 click
   }
});