一、效果图(不带确定按钮)
二、代码(着重看核心代码——Builder构建器创建)
package com.example.administrator.app_dialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化视图0
initView();
//设置点击事件0
myClick();
}
//初始化视图1
private void initView() {
btn1 = findViewById(R.id.btn1);
}
//设置点击事件1
private void myClick(){
btn1.setOnClickListener(this);
}
//设置点击事件2
//预先定义变量
int i = 0;
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn1:
//预先创建菜单数组
final String[] items = {"菜单一","菜单二","菜单三","菜单四","菜单五",};
//创建对话框——Dialog核心代码
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//设置标题
builder.setTitle("这是标题");
//设置菜单,参数1:选项;参数2:默认被选中项,传索引;参数3:点击事件
builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//设置点击事件,取得所选菜单的索引值,需要预先定义变量
i = which;
}
}).setPositiveButton("肯定按钮", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//点击确定按钮之后执行的任务
switch (i){
case 0:
Toast.makeText(MainActivity.this, "菜单一被选中", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(MainActivity.this, "菜单二被选中", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(MainActivity.this, "菜单三被选中", Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(MainActivity.this, "菜单四被选中", Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(MainActivity.this, "菜单五被选中", Toast.LENGTH_SHORT).show();
break;
}
}
});
//创建对话框
builder.create();
//显示对话框
builder.show();
break;
}
}
}
标签:Toast,菜单,对话框,安卓,show,单选,import,android,void From: https://blog.51cto.com/u_13272819/6079180