對話視窗元件提供應用程式與使用者互動,其中AlertDialog為警告視窗,當離開程式或是刪除檔案時會跳出,加以確認。
AlertDialog Builder屬性表
小試身手小範例:
在這個範例中,使用了兩個Button,各對兩個Button設置事件,一個為About()事件,一個為Leave()事件,然而這兩個Method都會定義其AlertDialog的屬性。
LinearLayout01.Java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class example0312 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button Button01 = (Button)findViewById(R.id.button01);
final Button Button02 = (Button)findViewById(R.id.button02);
Button01.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
About();
}
});
Button02.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Leave();
}
});
}
//顯示"about us"的對話視窗
private void About() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("about ").setMessage("This is Alert Dialog").show();
}
//顯示"leave us"的對話視窗
private void Leave() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Exit application?").setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//關閉程式
example0312.this.finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//關閉AlertDialog視窗
dialog.cancel();
}
});
AlertDialog about_dialog = builder.create();
about_dialog.show();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" about us "
android:layout_marginTop="50sp"
android:layout_marginLeft="100sp"
/>
<Button
android:id="@+id/button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" leave us "
android:layout_marginTop="20sp"
android:layout_marginLeft="100sp"
/>
</LinearLayout>
留言列表