AlertDialog选择对话框

时间:2022-11-01 13:39:49

转载请注明出处http://blog.csdn.net/mr_leixiansheng/article/details/53559605

AlertDialog选择对话框

区别:不用在xml定义,直接在活动中使用


package com.example.administrator.alertdialog;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//实例化一个 AlertDialog.Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//设置标题、内容、返回键是否退出、按键响应
builder.setTitle("对话选择框");
builder.setMessage("这是一个对话框,请进行选择");
builder.setCancelable(false);

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "你点击了OK", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
//必须显示出来
builder.show();
}
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

</LinearLayout>