我使用以下代码创建了自定义警告对话框 -
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog, null))
.setTitle("test")
.setCancelable(true);
AlertDialog alert11 = builder.create();
alert11.show();
以下是警告对话框中使用的布局dialog.xml的代码 -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"/>
</LinearLayout>
现在,如何获取按钮的引用来设置点击监听器?
我试过了 -
Button mButton = (Button) findViewById(R.id.button1);
但是我得到了一个例外 -
java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.Button.setText(java.lang.CharSequence)'
有没有其他方法可以访问该按钮?
答案 0 :(得分:1)
您可以像这样访问按钮
Button dialogButton = (Button) alert11.findViewById(R.id.button1);
答案 1 :(得分:1)
您正在寻找错误位置的按钮。
View view = inflater.inflate(R.layout.dialog, null);
builder.setView(view)
.setTitle("test")
.setCancelable(true);
然后使用view
寻找你的支柱
答案 2 :(得分:1)
您可以根据要求自定义完整警报对话框。请查看此答案.. Android - change dialog button location
答案 3 :(得分:1)
首先将自定义视图夸大为
View dialoglayout = inflater.inflate(R.layout.dialog, null);
然后使用dialoglayout
作为
builder.setView(dialoglayout)
.setTitle("test")
.setCancelable(true);
现在找到按钮
Button mButton = (Button) dialoglayout.findViewById(R.id.button1);
答案 4 :(得分:1)
在你的情况下使用
Button mButton = (Button)(inflater.inflate(R.layout.dialog, null)). findViewById(R.id.button1);
答案 5 :(得分:1)
使用此代码解决您的问题 -
View view = (LinearLayout) getLayoutInflater()
.inflate(R.layout.dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setView(view);
final AlertDialog mDialog = builder.create();
mDialog.setCancelable(false);
Button mButton = (Button) view.findViewById(R.id.button1);
mDialog.show();