歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中用兩層AlertDialog來進行彈出選擇框信息選擇

Android中用兩層AlertDialog來進行彈出選擇框信息選擇

日期:2017/3/1 10:39:56   编辑:Linux編程
在Android經常會用到AlertDialog,把內容使用AlertDialog結合列表的形式顯示出來,然後我們點擊得到點擊的信息。 這裡可以使用兩層的AlertDialog來實現

1:我們現在xml文件中定義一個要顯示內容列表數組

2:在Activity中使用 String[] items = getResources().getStringArray(R.array.item);

3:增添點擊事件,使用Alertdialog.builder 千萬不能忘了最後進行show()哦

直接看截圖的效果:

源代碼:

[java]

  1. package com.jiangqq.alertdialog;
  2. import android.app.Activity;
  3. import android.app.AlertDialog;
  4. import android.content.DialogInterface;
  5. import android.os.Bundle;
  6. import android.view.View;
  7. import android.view.View.OnClickListener;
  8. import android.widget.Button;
  9. /**
  10. * 使用AlertDialog進行選擇功能
  11. *
  12. * @author jiangqq
  13. *
  14. */
  15. public class AlertDialogActivity extends Activity {
  16. private Button btn;
  17. @Override
  18. public void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.main);
  21. btn = (Button) findViewById(R.id.btn);
  22. btn.setOnClickListener(new OnClickListener() {
  23. public void onClick(View v) {
  24. final String[] items = getResources().getStringArray(
  25. R.array.item);
  26. new AlertDialog.Builder(AlertDialogActivity.this)
  27. .setTitle("請點擊選擇")
  28. .setItems(items, new DialogInterface.OnClickListener() {
  29. public void onClick(DialogInterface dialog,
  30. int which) {
  31. new AlertDialog.Builder(
  32. AlertDialogActivity.this)
  33. .setTitle("你選擇了:" + items[which])
  34. .setMessage("點擊選擇操作")
  35. .setPositiveButton(
  36. "確定",
  37. new DialogInterface.OnClickListener() {
  38. public void onClick(
  39. DialogInterface dialog,
  40. int which) {
  41. // 這裡是你點擊確定之後可以進行的操作
  42. }
  43. })
  44. .setNegativeButton(
  45. "取消",
  46. new DialogInterface.OnClickListener() {
  47. public void onClick(
  48. DialogInterface dialog,
  49. int which) {
  50. // 這裡點擊取消之後可以進行的操作
  51. }
  52. }).show();
  53. }
  54. }).show();
  55. }
  56. });
  57. }
  58. }

string.xml文件內容:

[html]

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <string name="hello">Hello World, AlertDialogActivity!</string>
  4. <string name="app_name">Hello World, AlertDialogActivity</string>
  5. <string name="btn_name">點擊彈出AlertDialog</string>
  6. <string-array name="item">
  7. <item>第一個選擇</item>
  8. <item>第二個選擇</item>
  9. <item>第三個選擇</item>
  10. <item>第四個選擇</item>
  11. </string-array>
  12. </resources>
Copyright © Linux教程網 All Rights Reserved