android实现使用AlertDialog.Builder创建对话框加载Layout布局,添加两个TextView水平居中,以及四个RadioButton,并且给四个RadioButton添加点击事件,Dialog有取消以及确定按钮
时间: 2024-03-09 07:49:39 浏览: 200
android 使用alertdialog创建自定义对话框
4星 · 用户满意度95%
好的,以下是实现的代码示例:
```
// 获取LayoutInflater对象
LayoutInflater inflater = LayoutInflater.from(context);
// 加载对话框布局
View view = inflater.inflate(R.layout.dialog_layout, null);
// 创建AlertDialog.Builder对象
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// 设置对话框布局
builder.setView(view);
// 获取TextView和RadioButton控件
TextView textView1 = view.findViewById(R.id.text_view1);
TextView textView2 = view.findViewById(R.id.text_view2);
RadioButton radioButton1 = view.findViewById(R.id.radio_button1);
RadioButton radioButton2 = view.findViewById(R.id.radio_button2);
RadioButton radioButton3 = view.findViewById(R.id.radio_button3);
RadioButton radioButton4 = view.findViewById(R.id.radio_button4);
// 设置TextView文本
textView1.setText("TextView1");
textView2.setText("TextView2");
// 设置RadioButton文本
radioButton1.setText("RadioButton1");
radioButton2.setText("RadioButton2");
radioButton3.setText("RadioButton3");
radioButton4.setText("RadioButton4");
// 给RadioButton添加点击事件
radioButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when radioButton1 is clicked
}
});
radioButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when radioButton2 is clicked
}
});
radioButton3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when radioButton3 is clicked
}
});
radioButton4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something when radioButton4 is clicked
}
});
// 设置对话框的确定按钮
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do something when the positive button is clicked
}
});
// 设置对话框的取消按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do something when the negative button is clicked
}
});
// 创建对话框并显示
AlertDialog dialog = builder.create();
dialog.show();
```
在代码中,我们通过`builder.setPositiveButton`方法和`builder.setNegativeButton`方法添加了对话框的确定按钮和取消按钮,并分别给它们设置了点击事件的回调函数。你可以根据实际需求来修改这些回调函数的实现。
阅读全文