Android入門--彈出三個按鈕的對話方塊
阿新 • • 發佈:2019-02-19
在GUI程式中,有時需要彈出對話方塊來提示一些資訊。
這些對話方塊比一個獨立的螢幕簡單,在Android中彈出式對話方塊不同於表示一個螢幕的活動,它通常用於簡單的功能處理。
對話方塊的父類是android.app.Dialog,通過構建類android.app.AlertDialog來實現彈出式對話方塊,可以使用AlertDialog.Builder和不同的引數來構建對話方塊。
效果如下圖所示:
activity_forwarding.xml程式碼如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.forwarding.Forwarding" > <Button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="@string/Btn01" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button1" android:layout_marginTop="20dp" android:text="@string/Texts" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout>
Forwarding.java程式碼如下:
package com.example.forwarding; import android.support.v7.app.ActionBarActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Forwarding extends ActionBarActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forwarding); final Button dialogButton = (Button) findViewById(R.id.button1); final TextView texts = (TextView) findViewById(R.id.textView1); dialogButton.setOnClickListener(new View.OnClickListener() {// 按鍵單擊事件 @Override public void onClick(View v) { // TODO Auto-generated method stub new AlertDialog.Builder(Forwarding.this) .setTitle("系統提示") // 設定對話方塊標題 .setMessage("請確認所有資料都儲存後再推出系統!") // 設定顯示的內容 //右邊按鈕 .setPositiveButton("確定", new DialogInterface.OnClickListener() {// 新增確定按鈕 @Override public void onClick( DialogInterface dialog, int which) {// 確定按鈕的響應事件 // TODO Auto-generated method // stub //finish(); texts.setText("結果:確認 "); } }) //中間按鈕 .setNeutralButton("測試", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { texts.setText("結果:測試 "); } }) //左邊按鈕 .setNegativeButton("返回", new DialogInterface.OnClickListener() {// 新增返回按鈕 @Override public void onClick( DialogInterface dialog, int which) {// 響應事件 // TODO Auto-generated method // stub //Log.i("alertdialog", " 請儲存資料!"); texts.setText("結果:返回 "); } }).show();// 在按鍵響應事件中顯示此對話方塊 } }); } }