业务需求:
点击供应商选择按钮出现对话框,选择供应商后tv控件显示选择的供应商名称,点击确定,对话框消失。
public class MainActivity extends AppCompatActivity {
private TextView tvaMainTitle;
private Button btnMainClose;
private Button btnMainSupplier;
private TextView tvMainResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
btnMainSupplier.setOnClickListener(new View.OnClickListener() {
String[] suppliers=new String[]{"供应商1", "供应商2", "供应商3"};
@Override
public void onClick(View v) {
//匿名对象 方法链 前提:方法返回值是本对象 不断的去调用方法,不加; 看返回值
new AlertDialog.Builder(MainActivity.this)//不加;
.setTitle("选择供应商") //不加;
.setSingleChoiceItems(suppliers,0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
tvMainResult.setText(suppliers[which]);
}
})
.setPositiveButton("确定", null) //不加;
.create()
.show();
// // 1创建对象
// AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
// //2、设置标题、内容和按钮区域
// builder.setTitle("选择供应商");
// builder.setPositiveButton("确定",null);
// //3.创建对话框
// AlertDialog alertDialog=builder.create();
// alertDialog.show();
}
});
btnMainClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//弹出对话框
//对话框步骤:
//创建Builder构建器
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
//2、设置标题内容和按钮区域
builder.setTitle("对话框标题");
builder.setIcon(R.drawable.ic_launcher_background);
builder.setMessage("普通对话框");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();//关闭对话框
MainActivity.this.finish();//关闭Activity
}
});
builder.setNegativeButton("取消", null);//功能一样,直接置空
builder.setNeutralButton("中立", null);
//3.创建对话框,然后显示
AlertDialog dialog = builder.create();
// dialog.setTitle("对话框标题");
// dialog.setMessage("普通对话框");
// dialog.setButton(Dialog.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// MainActivity.this.finish();
// }
// });
dialog.setMessage("普通对话框");
dialog.show();
}
});
}
private void initView() {
tvaMainTitle = (TextView) findViewById(R.id.tvaMainTitle);
btnMainClose = (Button) findViewById(R.id.btnMainClose);
btnMainSupplier = (Button) findViewById(R.id.btnMainSupplier);
tvMainResult = (TextView) findViewById(R.id.tvMainResult);
}
}
效果图:
原创文章 6获赞 2访问量 532
关注
私信
展开阅读全文
作者:Liekkas Yu