[英]Cannot access elements inside included layout: Android
I have an xml file which contains a button and its called button/xml 我有一个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" />
I have another layout called login.xml , which includes the button.xml in it twice. 我还有另一个名为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>
Now when I try to access each of the buttons seperately in my Java class, I get an error while pointing to loginUser1 . 现在,当我尝试分别访问Java类中的每个按钮时,在指向loginUser1时出现错误。 The error says NullPointerException .
该错误显示NullPointerException 。 Since I know for sure that loginUser1 exists, why am I still getting the error?
既然我确定知道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");
Check out your log cat. 查看您的日志猫。 You should get
ClassCastException
instead of NullPointerException
. 您应该获取
ClassCastException
而不是NullPointerException
。 The problem is that view with id R.id.loginUser1
is actually a Button
and not a LinearLayout
. 问题是ID为
R.id.loginUser1
视图实际上是一个Button
而不是LinearLayout
。 The following code should work well: 以下代码应该可以正常工作:
final Button first = (Button) findViewById(R.id.loginUser1);
final Button second = (Button) findViewById(R.id.loginUser2);
first.setText("button one");
second.setText("button two");
Also, please note that there is no button with id R.id.loginButton1
anymore because its id was overridden by include
tag 另外,请注意,不再有ID为
R.id.loginButton1
按钮,因为其ID被include
标签覆盖了
You should do this 你应该做这个
final Button first = (Button) findViewById(R.id.loginButton1); 最终的按钮优先=(按钮)findViewById(R.id.loginButton1); first.setText("your text");
first.setText(“您的文本”);
as loginUser1 is a button and not a LinearLayout. 因为loginUser1是一个按钮,而不是LinearLayout。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.