[英]Android: NullPointerException being thrown on Button call?
我不知道为什么,但是在任何时候我都会不断调用E/AndroidRuntime(709): java.lang.NullPointerException
,我尝试调用标题为yes和no的按钮。 这些按钮以xml布局创建,并使用findViewById
方法进行调用,这是我在同一程序中的几个可正常工作的按钮中使用的类似技术。 这些按钮与其余按钮之间的唯一区别在于,它们的xml代码保存在一个单独的布局文件中,而不是main.xml。
如果我只想显示按钮而不在Java代码中调用它们,它们将按应有的方式显示。 当我试图在Java代码中,如任何适用于他们出现的错误setClickable()
和setOnClickListener()
下面的代码概述了xml中按钮和布局的创建,而Java代码显示了一种在调用时创建弹出窗口的方法。
Java代码:
private void getLogoutOption() {
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.logoutoption, null);
final PopupWindow logoutoption = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button yes = (Button) findViewById (R.id.yes);
yes.setClickable(true);
yes.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
logoutoption.dismiss();
switchActivity(8);
}
});
Button no = (Button) findViewById (R.id.no);
no.setClickable(true);
no.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
logoutoption.dismiss();
}
});
logoutoption.showAsDropDown(search, 50, -30);
}
XML代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/transparent" >"
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/menu_default" >
<TextView
android:id="@+id/logoutmessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Are you sure you would like to logout?"
android:textColor="@color/gold" />
<Button
android:id="@+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/logoutmessage"
android:layout_centerInParent="true"
android:text="YES"
android:textColor="@color/green" />
<Button
android:id="@+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/logoutmessage"
android:layout_toRightOf="@id/yes"
android:text="NO"
android:textColor="@color/red" />
</RelativeLayout>
</RelativeLayout>
Button yes = (Button) findViewById (R.id.yes);
应该
Button yes = (Button) popupView.findViewById (R.id.yes);
默认情况下, findViewById()
将在内容视图中搜索具有指定ID的视图(例如,如果您使用setContentView(R.layout.main)
,它将在main.xml结构中搜索那些视图)。 如果要搜索膨胀的布局,则必须在该特定的膨胀的布局上调用findViewById()
。
更改:
Button yes = (Button) findViewById (R.id.yes);
Button no = (Button) findViewById (R.id.no);
至:
Button yes = (Button) popupView.findViewById (R.id.yes);
Button no = (Button) popupView.findViewById (R.id.no);
嗨,问题是您在Activity中获取ID。在setContentView(R.layout.main)创建的Activity视图中。在代码中,您正在膨胀新视图,因此您应该使用
按钮yes =(Button)popupView.findViewById(R.id.yes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.