Android开发中提示框Toast、AlertDialog的使用!
先了解一下AlertDialog.Builder创建对话框的几个常用方法:
setTitle() :设置标题
setIcon() :设置图标
setMessage():设置提示内容
setView() : 设置自定义视图
setItems() :设置对话框要显示的一个list
setMultiChoiceItems() :设置对话框显示的复选框
setNeutralButton() :普通按钮
setPositiveButton() :添加"Yes"按钮
setNegativeButton() :添加"No"按钮
create() : 创建对话框
show() :显示对话框
下面以一个例子简单演示一下其应用,先看一下效果图:
Toast的使用效果:
AlertDialog的简单使用:
类似于ListView的效果:
类似于RadioButton的效果:
多选的效果:
自定义视图:
代码示例如下:
一个主activity,两个布局文件;
ReviewCriteria.java
[java]
package com.test.restaurantfinder;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInte易做图ce;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ReviewCriteria extends Activity {
private static final String tag = "reviewCriteria";
private final String arrayFruit[] = new String[]{"apple","banana","pear"};
private Button tishiButton = null; //提示Toast的按钮
private Button tishiAlert = null; //普通AlertDialog
private Button tishiAlertItem = null; //类似ListItem
private Button AlertRadio = null; //类似RadioButton
private int selectedFruitIndex = 0;
private Button CheckButton = null; //类似CheckBox
final boolean[] arrayFruitSelected = new boolean[] {false, true, false}; //默认选中
private Button myCustomButton = null; //自定义视图
private View myCustomView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review_criteria);
this.tishiButton = (Button)findViewById(R.id.tishiButton);
this.tishiAlert = (Button)findViewById(R.id.tishiAlart);
this.tishiAlertItem = (Button)findViewById(R.id.AlertItem);
this.AlertRadio = (Button)findViewById(R.id.AlertSingleChoice);
this.CheckButton = (Button)findViewById(R.id.AlertCheckBox);
this.myCustomButton = (Button)findViewById(R.id.customView);
//Toast
this.tishiButton.setOnClickListener(
new OnClickListener(){
@Override
public void onClick(View v){
Log.i(tag, "in onClick1");
/*注:在内嵌函数中使用时context 一定要对,不能只是this,而应该是Class.this或者getApplicationContext()*/
//Toast.makeText(ReviewCriteria.this, "this is a toast", Toast.LENGTH_LONG).show();
Toast toast = Toast.makeText(ReviewCriteria.this, "this is a toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
//AlertDialog
this.tishiAlert.setOnClickListener(
new OnClickListener(){
public void onClick(View v){
new AlertDialog.Builder(ReviewCriteria.this).
setIcon(R.drawable.ic_launcher).//图标
setTitle("Delete?").//标题
setMessage("this is a AlertDialog!").//提示内容
setPositiveButton("Yes", new DialogInte易做图ce.OnClickListener() {//确定
@Override
&
补充:移动开发 , Android ,