Android中要顯現對話框需使用AlterDialog.Builder類,還可以自定義對話框。對話框如果存在按鈕,還需要對其設置事件監聽OnClickListener。
使用AlterDialog.Builder傳幾個鍵對話框用到的幾個方法:
setTitle() 設置對話框標題
setIcon()設置對話框圖標
setMessage()設置對話框提示信息
setItems()設置對話框要顯示的一個list,一般用於顯示幾個命令時
setSingleChoiceItems()設置對話框顯示一個單選的list
setMultiChoiceItems()設置對話框顯示一系列的複選框
setPositiveButton()添加yes按鈕
setNegativeButton()添加NO按鈕
下面的的例子分別建立了一個打兩個按鈕的對話框和一個帶進度條的對話框!
myDialogActivity.java
package cn.myDialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;
import android.widget.TextView;
public class myDialogActivity extends Activity {
ProgressDialog mDialog;
ImageView imageView1,imageView2;
TextView textView;
int imag_alpha=255;
boolean isrung=false;
Handler mHandler=new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView1=(ImageView) findViewById(R.id.image1);
imageView2=(ImageView) findViewById(R.id.image2);
textView=(TextView) findViewById(R.id.textview1);
// textView.setText("現在alpha的值是:"+Integer.toString(imag_alpha));
Dialog dialog=new AlertDialog.Builder(this).setTitle(" 登錄提示")
.setMessage("這裏需要登錄")
.setPositiveButton("確定", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
isrung=true;
imageView1.setImageResource(R.drawable.wee);
imageView2.setImageResource(R.drawable.dd);
imageView1.setAlpha(imag_alpha);
imageView2.setAlpha(imag_alpha);
new Thread(new Runnable() {
public void run() {
while (isrung) {
try {
Thread.sleep(200);
updateAlpha();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
mHandler=new Handler(){
public void handleMessage(Message msg) {
super.handleMessage(msg);
imageView1.setAlpha(imag_alpha);
textView.setText("現在alpha的值是:"+Integer.toString(imag_alpha));
imageView1.invalidate();
}
};
}
}).setNegativeButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
myDialogActivity.this.finish();
}
}).setIcon(R.drawable.dd).show();
mDialog=ProgressDialog.show(myDialogActivity.this, "請稍等", "正在爲你處理...",true);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (Exception e) {
// TODO: handle exception
}
finally
{mDialog.dismiss();}
}
}).start();
}
public void updateAlpha(){
if (imag_alpha-7>=0) {
imag_alpha-=7;
}
else{
imag_alpha=0;
isrung=false;
}
mHandler.sendMessage(mHandler.obtainMessage());
}
}