讲述具有相同ID的两个Android GUI对象之间的差异

时间:2014-07-26 06:35:30

标签: java android android-studio android-4.2-jelly-bean

假设我们有两个XML文件,其中包含以下片段:

firstxml.xml

<?xml version="1.0" encoding="utf-8"?>
<Button
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/button1 />

secondxml.xml

<?xml version="1.0" encoding="utf-8"?>
<Button
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/button1 />

在我们的onCreate()方法中:

//Assume all packages necessary are imported
public class Example
{
    public void onCreate(Bundle sis)
    {
      super.onCreate(sis);
      setContentView(R.layout.firstxml);

      Button thisButton = (Button) findViewbyId(R.id.button1);

    }
}

当此代码运行时,调用哪个按钮并实例化?由于这两个按钮位于两个不同的文件中,是否会调用firstxml.xml中的按钮,因为它是函数的内容视图?

提前感谢您的回答!

4 个答案:

答案 0 :(得分:2)

当您将firstxml设置为内容视图时,该布局会膨胀。 findViewById将在当前布局中找到膨胀而不是在每个布局上的id。

setContentView方法说明可以回答您的问题。

答案 1 :(得分:1)

代码将调用并实例化firstxml.xml文件中设置的button1。

注意对于未来的读者。如果布局文件不包含button1,它将抛出空指针异常,编辑器不会知道存在错误。这是因为 R.id.button1 是R.java类中的静态字段。还为变量提供了更好的命名约定,以实现可维护性。

答案 2 :(得分:1)

Which button is called and instantiated when this code runs? 

由于您使用firstxml.xml作为活动的布局,因此您从该xml调用该按钮的引用而不是secondxml.xml中的按钮。

在您的R.java中,它只会生成该id的一个实例。

<强>样品:

public static final class id {
    public static final int button1=0x7f090009;
}

因此,当您使用该按钮的引用时,它将首先查找/检查布局的ID(如果它存在,如果它不存在则会抛出 NPE )。

答案 3 :(得分:1)

您正在引用活动的R.layout.firstxml方法中的第一个XML布局文件onCreate(Bundle...),因此将在此处进行搜索。

findViewById(int id);的任何来电都会搜索您的虚增布局R.layout.firstxml

在为布局定义/添加新视图时,会自动生成R.java文件。

您可以多次使用相同的ID,但不在同一个布局中