第一步先写出layout文件

AlterDialog对话框的使用-LMLPHP

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"> <TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="单选对话框"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:textColor="#fffdb371"/> <Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="设置字体大小"
android:layout_marginTop="20dp"
android:layout_gravity="center"/> </LinearLayout>

第二步写MainActity

AlterDialog对话框的使用-LMLPHP

package com.iang.dialongdemo;

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.TextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private TextView textView;
private int[] textSizeArr={10,20,25,30,40};
int textSize=1;
// 加载资源文件,找到资源文件中的按钮id号
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.linear);
findViewById(R.id.bt).setOnClickListener(this);
textView=(TextView) findViewById(R.id.tv);
} @Override
public void onClick(View v) {
AlertDialog dialog;
AlertDialog.Builder builder=new AlertDialog.Builder(this)
.setTitle("设置字体大小")
.setIcon(R.mipmap.ic_launcher)
.setSingleChoiceItems(new String[]{"小号", "默认", "中号", "大号", "超大"}, textSize, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
textSize=which;
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
textView.setTextSize(textSizeArr[textSize]);
dialog.dismiss();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
// 回退程序的使用
@Override
public void onBackPressed() {
// super.onBackPressed();
AlertDialog dialog;
AlertDialog.Builder builder =new AlertDialog.Builder(this)
.setTitle("普通对话框") //设置对话框的标题
.setIcon(R.mipmap.ic_launcher) //设置标题图标
.setMessage("是否确定退出应用:")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
MainActivity.this.finish();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = builder.create();
dialog.show();
}
}

第三步完成

AlterDialog对话框的使用-LMLPHP

AlterDialog对话框的使用-LMLPHP

AlterDialog对话框的使用-LMLPHP

AlterDialog对话框的使用-LMLPHP

05-11 18:27