Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android AlertDialog 示例二:普通單選項對話框

編輯:關於 Android 開發

Android AlertDialog 示例二:普通單選項對話框


在 Android 開發中,我們常常需要在界面上彈出對話框來詢問用戶或讓其做出選擇,這類功能被稱為 Android Dialog,而 AlertDialog 採用的是建造者(Builder)模式。下面我們模擬一個「選花魁」的普通單選對話框,效果如下圖:

Layout 界面代碼:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:text="普通選項" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="show2" android:id="@+id/button2" /> </LinearLayout>

Java 功能實現代碼:

public class AlertDialogDemo extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alertdialog); } public void show2(View v){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("選花魁喽"); final String[] beautifulGirls = {"芙蓉姐姐","鳳姐","范爺","我自己"}; builder.setItems(beautifulGirls, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(AlertDialogDemo.this,beautifulGirls[which]+"被選中啦",Toast.LENGTH_SHORT).show(); } }); builder.show(); } }

核心思路是:先用 Builder 設置標題,再用 setItems 傳入字符串數組並綁定點擊事件,最後調用 show() 顯示。點擊某項後,即可通過 which 索引獲知用戶的選擇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved