Android对话框
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 }
好看请赞,养成习惯:) 本文来自博客园,作者:靠谱杨, 转载请注明原文链接:https://www.cnblogs.com/rainbow-1/p/14364393.html
欢迎来我的51CTO博客主页踩一踩 我的51CTO博客
文章中的公众号名称可能有误,请统一搜索:靠谱杨的秘密基地