From:http://blog.csdn.net/dazlly/article/details/7869204#
首先简单对话框,分为三部分:标题,内容和下面的按键,先看没有按键的对话框的声明方式:
new AlertDialog.Builder(Main.this).setTitle("标题").setMessage("内容").show();
public AlertDialog.Builder setPositiveButton (CharSequence text, DialogInterface.OnClickListener listener)
public AlertDialog.Builder setNegativeButton (CharSequence text, DialogInterface.OnClickListener listener)
public AlertDialog.Builder setNeutralButton (CharSequence text, DialogInterface.OnClickListener listener)
new AlertDialog.Builder(Main.this).setTitle("标题").setMessage("内容")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//这里编写点击对话框按钮后触发的事件
}
}).show();
public AlertDialog.Builder setItems (CharSequence[] items, DialogInterface.OnClickListener listener)
- 篮球
- 足球
- 棒球
- 乒乓球
new AlertDialog.Builder(Main.this)
.setTitle("标题")
.setItems(R.array.sports,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int itemId) {
//这里编写点击对话框按钮后触发的事件
}
}).show();
Toast.makeText(Main.this, "就这么简单", Toast.LENGTH_SHORT).show();
三种对话框结合起来写个简单示例:
package com.dazlly;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class Main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
setListener();
}
private Button firstButton;
private void findViews() {
firstButton = (Button) findViewById(R.id.firstButton);
}
private void setListener() {
firstButton.setOnClickListener(show);
}
private Button.OnClickListener show = new Button.OnClickListener() {
@Override
public void onClick(View arg0) {
new AlertDialog.Builder(Main.this)
.setTitle(R.string.title)
.setMessage(R.string.message)
.setNegativeButton(R.string.back,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
})
.setPositiveButton(R.string.go,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int itemId) {
showList();
}
}).show();
}
};
private void showList() {
new AlertDialog.Builder(Main.this)
.setTitle(R.string.list)
.setItems(R.array.sports,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
String[] list = getResources().getStringArray(
R.array.sports);
Toast.makeText(Main.this, "你选择了" + list[which],
Toast.LENGTH_SHORT).show();
}
}).show();
}
}