无法访问包含布局内的元素:Android

时间:2013-02-17 04:46:48

标签: android xml include

我有一个xml文件,其中包含一个按钮,名为 button / xml

<Button
    android:id="@+id/loginButton1"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:background="@drawable/button_background"
    android:text="Button" />

我有另一个名为 login.xml 的布局,其中包含了两次button.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" 
    android:paddingLeft="30dp"
    android:paddingRight="30dp"
    android:paddingTop="30dp">

    <include
        android:id="@+id/loginUser1"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        layout="@layout/button" />

        <include
            android:id="@+id/loginUser2"
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:layout_marginTop="20dp"
            layout="@layout/button" />

</LinearLayout>

现在,当我尝试在Java类中单独访问每个按钮时,指向 loginUser1 时出现错误。错误显示 NullPointerException 。既然我确定loginUser1存在,为什么我仍然会收到错误?

    final LinearLayout layout = (LinearLayout)findViewById(R.id.loginUser1); //null pointer exception HERE!
    final Button button = (Button)layout.findViewById(R.id.loginButton1);
    button.setText("button one");

2 个答案:

答案 0 :(得分:2)

查看您的日志猫。您应该ClassCastException而不是NullPointerException。问题是ID为R.id.loginUser1的视图实际上是Button而不是LinearLayout。以下代码应该可以正常运行:

final Button first = (Button) findViewById(R.id.loginUser1);
final Button second = (Button) findViewById(R.id.loginUser2);

first.setText("button one");
second.setText("button two");

此外,请注意,不再有ID为R.id.loginButton1的按钮,因为其ID已被include标记覆盖

答案 1 :(得分:0)

你应该这样做

final Button first =(Button)findViewById(R.id.loginButton1); first.setText(“your text”);

因为loginUser1是一个按钮而不是LinearLayout。

相关问题