同Windows程序类似,对话框是Activity运行时显示在前台的小窗口,用于显示消息或让用户做某些选择等。Android中主要包括提示对话框、选项对话框、单选多选对话框、日期与时间对话框、进度条对话框等
Dialog 类是对话框的基类,但应该避免直接实例化 Dialog,而应使用其子类,比如
AlertDialog
此对话框可显示标题、提示信息、按钮、可选择项列表或自定义布局等
DatePickerDialog 或 TimePickerDialog
此类对话框带有允许用户选择日期或时间的预定义UI
简单对话框
AlertDialog.Builder builder = null;
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(“第一个对话框”)
.setIcon(R.drawable.google)
.setMessage(“你好,对话框”)
.setPositiveButton(“确认”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, “好的”,
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(“取消”, null)
.setNeutralButton("忽略",null)
.show();
单选按钮对话框
在列表对话框中,显示内容为一个列表,允许用户在多个选项中选择一个且只能选择一个
在string.xml中定义
<array name="Color">
<item >Red</item>
<item>Blue</item>
<item>Green</item>
<item>Gray</item>
</array>
在代码中
items = getResources().getStringArray(R.array.Color);
builder = new AlertDialog.Builder(MainActivity.this);
final int []tmp=new int[]{Color.RED,Color.BLUE,Color.GREEN,Color.GRAY};
builder.setTitle(“颜色选择”)
.setIcon(R.drawable.user_woman)
.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
tv.setText(items[which] + “ 选择了”);
tv.setBackgroundColor(tmp[which]);
}
}) .show();
复选框对话框
tmp2String = getResources().getStringArray(R.array.hobby);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
tmp2 = new boolean[]{true, false, false};
builder.setTitle("多选对话框")
.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
tv.setText("");
for (int i = 0; i < tmp2.length; i++)
if (tmp2[i]) tv.append(" " + tmp2String[i]);
}
}).setNegativeButton("取消", null)
.setMultiChoiceItems(R.array.hobby, tmp2
, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked)
tmp2[which] = true;
else
tmp2[which] = false;
}
})
.show();
ProgressDialog可以显示进度。可以设置进度条的样式。
tmp=0;
final ProgressDialog dialog=new ProgressDialog(MainActivity.this);
dialog.setMax(100);
dialog.setIcon(R.drawable.user_woman);
dialog.setTitle("下载文件");
dialog.setMessage("下载完成后,自动关闭");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
new Thread(){
@Override
public void run() {
while(tmp<=100){
tmp=tmp+5;
try {
dialog.setProgress(tmp);
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
dialog.dismiss();
}
}.start();
日期和时间对话框
TimePickerDialog dialog=new TimePickerDialog(MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
tv.setText(hourOfDay+"时"+minute+"分");
}
},8,24,true);
dialog.show();
Calendar calendar=Calendar.getInstance();
DatePickerDialog dialog=new DatePickerDialog(MainActivity.this
,new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
tv.setText(year+"年"+(month+1)+"月"+dayOfMonth+"日");
}
},calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get( Calendar.DAY_OF_MONTH));
dialog.show();
自定义对话框
定义对话框布局login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/name"
android:hint="输入姓名"
android:inputType="text"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/pass"
android:inputType="textPassword"
android:hint="输入密码"/>
</LinearLayout>
在生成对话框是加载布局,并指定监听事件即可。
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView text1;
EditText name,password;
Button login1;
RadioButton sex1,sex2;
TableLayout tableLayout;
CheckBox []checkBoxes;
Switch switch1;
ProgressBar bar,bar2;
SeekBar seekBar;
String []hobby=new String[]{
"游泳","乒乓球","吃鸡","王者","拳击"
};
String []hobbys;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test1);
text1=findViewById(R.id.text1);
name=findViewById(R.id.name);
password=findViewById(R.id.password);
sex1=findViewById(R.id.sex1);
sex2=findViewById(R.id.sex2);
tableLayout=findViewById(R.id.table);
hobbys=getResources().getStringArray(R.array.hobby);
switch1=findViewById(R.id.switch1);
bar=findViewById(R.id.progressBar);
bar2=findViewById(R.id.progressBar2);
seekBar=findViewById(R.id.seekbar);
// seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
// @Override
// public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// text1.setTextSize(progress);
//
// }
//
// @Override
// public void onStartTrackingTouch(SeekBar seekBar) {
//
// }
//
// @Override
// public void onStopTrackingTouch(SeekBar seekBar) {
//
// }
// });
bar.setMax(100);
new Thread(){
public void run(){
for(int i=0;i<=100;i++){
bar.setProgress(i);
try{
sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}.start();
sex1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Toast.makeText(MainActivity.this,
"已选择男生 ",Toast.LENGTH_SHORT).show();
}
}
});
sex2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
Toast.makeText(MainActivity.this,
"已选择女生",Toast.LENGTH_SHORT).show();
}
}
});
login1=findViewById(R.id.login);
// MyListener myListener=new MyListener();
// login1.setOnClickListener(myListener);
// login1.setOnClickListener(new View.OnClickListener(){
// @Override
// public void onClick(View v){
// String tmp="爱好";
// for(int i=0;i<checkBoxes.length;i++){
// if(checkBoxes[i].isChecked()){
// tmp+=checkBoxes[i].getText()+"";
// }
// }
// if(sex1.isChecked()){
// tmp+="性别男";
// }
// else if(sex2.isChecked()){
// tmp+="性别女";
// }
// if(switch1.isChecked()){
// tmp+="开关:开";
// }
// else{
// tmp+="开关:关";
// }
// Toast.makeText(MainActivity.this,
// name.getText()+" "+
// password.getText()+" "+tmp,Toast.LENGTH_SHORT).show();
//
//
// }
// });
init();
}
private void init(){
checkBoxes=new CheckBox[hobbys.length];
for(int i=0;i<hobbys.length;i+=4){
TableRow row=new TableRow(this);
for(int j=0;j<4&&i+j<hobbys.length;j++){
checkBoxes[i+j]=new CheckBox(this);
checkBoxes[i+j].setText(hobbys[i+j]);
row.addView(checkBoxes[i+j]);
}
tableLayout.addView(row);
}
}
public void onClick(View v){
switch(v.getId()){
case R.id.login:
break;
}
}
class MyListener implements View.OnClickListener{
public void onClick(View v){
String tmp="爱好";
for(int i=0;i<checkBoxes.length;i++){
if(checkBoxes[i].isChecked()){
tmp+=checkBoxes[i].getText()+"";
}
}
if(sex1.isChecked()){
tmp+="性别男";
}
else if(sex2.isChecked()){
tmp+="性别女";
}
if(switch1.isChecked()){
tmp+="开关:开";
}
else{
tmp+="开关:关";
}
Toast.makeText(MainActivity.this,
name.getText()+" "+
password.getText()+" "+tmp,Toast.LENGTH_SHORT).show();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/text1"
android:textSize="@dimen/MyFont"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="to"
android:background="@color/MyRed"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="subject"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="content"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="cancel"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="send"/>
</LinearLayout>
</LinearLayout>