layout.xml文件

1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:orientation="vertical"
6 >
7 <Button
8 android:id="@+id/bt_alert"
9 android:layout_width="wrap_content"
10 android:layout_height="wrap_content"
11 android:text="显示对话框!"
12
13
14 />
15 <Button
16 android:id="@+id/btn_single"
17 android:layout_width="wrap_content"
18 android:layout_height="wrap_content"
19 android:text="这是一个单选按钮"
20 />
21 </LinearLayout>

activity.java文件

1 package com.example.myapplication;
2
3 import android.content.DialogInterface;
4 import android.os.Bundle;
5 import android.view.View;
6 import android.widget.Button;
7 import android.widget.Toast;
8 import androidx.annotation.Nullable;
9 import androidx.appcompat.app.AppCompatActivity;
10
11 public class AlertDialog extends AppCompatActivity implements View.OnClickListener{
12 @Override
13 protected void onCreate(@Nullable Bundle savedInstanceState) {
14 super.onCreate(savedInstanceState);
15 setContentView(R.layout.activity_alert);
16 Button bt_alert=findViewById(R.id.bt_alert);
17 Button btn_single=findViewById(R.id.btn_single);
18 bt_alert.setOnClickListener(this);
19 btn_single.setOnClickListener(this);
20 }
21 @Override
22 public void onClick(View v) {
23 androidx.appcompat.app.AlertDialog.Builder builder=new androidx.appcompat.app.AlertDialog.Builder(this);
24 switch (v.getId())
25 {
26 case R.id.bt_alert:
27 builder.setTitle("对话框").setIcon(R.mipmap.ic_launcher).setMessage("Drink some small beer!")
28 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
29 @Override
30 public void onClick(DialogInterface dialog, int which) {
31 Toast.makeText(AlertDialog.this,"Yes,your treat!",Toast.LENGTH_SHORT).show();
32 }
33 })
34 .setNegativeButton("No", new DialogInterface.OnClickListener() {
35 @Override
36 public void onClick(DialogInterface dialog, int which) {
37 Toast.makeText(AlertDialog.this,"I've no time,sorry!",Toast.LENGTH_SHORT).show();
38 }
39 });
40 case R.id.btn_single:
41 builder.setTitle("单选对话框").setIcon(R.mipmap.ic_launcher).setSingleChoiceItems(new String[]{}, 0, new DialogInterface.OnClickListener() {
42 @Override
43 public void onClick(DialogInterface dialog, int which) {
44 Toast.makeText(AlertDialog.this,"选中的",Toast.LENGTH_SHORT).show();
45 }
46 });
47 }
48 }
49

 

作者:​​靠谱杨​​​, ​

更多日常分享尽在我的VX公众号:小杨的挨踢IT生活

Android对话框_ide