歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發教程:對話框淺析

Android開發教程:對話框淺析

日期:2017/3/1 10:36:37   编辑:Linux編程
對話框式程序運行中彈出的窗口。Android系統中有四種默認的對話框:警告對話框AlertDialog、進度對話框ProgressDialog、日期選擇對話框DatePickerDialog以及時間選擇對話框TimePickerDialog。除此之外,我們自定義自已的dialog。

一. 警告對話框(AlertDialog)

Android系統中最常用的對話框是AlertDialog,它是一個提示窗口,需要用戶作出選擇的。一般會有幾個按鈕、標題信息、提示信息等。

在程序中創建AlertDialog的步驟:

1.獲得AlertDialog的靜態內部類Builder對象,由該類來創建對話框,Builder所提供的方法如下:

setTitle():給對話框設置title.

setIcon():給對話框設置圖標。

setMessage():設置對話框的提示信息

setItems():設置對話框要顯示的一個list,一般用於要顯示幾個命令時

setSingleChoiceItems():設置對話框顯示一個單選的List

setMultiChoiceItems():用來設置對話框顯示一系列的復選框。

setPositiveButton():給對話框添加”Yes”按鈕。

setNegativeButton():給對話框添加”No”按鈕。

2.調用Builder的create( )方法

3.調用AlertDialog的show( )方法顯示對話框

下面是一個提示信息對話框的實例:

AlertDialogActivity.java

  1. package com.android.dialog.activity;
  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. import android.widget.TextView;
  10. public class AlertDialogActivity extends Activity {
  11. private TextView tv;
  12. private Button btn;
  13. @Override
  14. public void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.main);
  17. tv = (TextView)findViewById(R.id.TextView_1);
  18. btn = (Button)findViewById(R.id.Button_1);
  19. //實例化AlertDialog.Builder對象
  20. final AlertDialog.Builder builder = new AlertDialog.Builder(this);
  21. btn.setOnClickListener(new OnClickListener() {
  22. public void onClick(View v) {
  23. //設置提示信息,確定按鈕
  24. builder.setMessage("真的要刪除該文件嗎?").setPositiveButton("是", new DialogInterface.OnClickListener() {
  25. public void onClick(DialogInterface dialog, int which) {
  26. tv.setText("成功刪除");
  27. }
  28. //設置取消按鈕
  29. }).setNegativeButton("否", new DialogInterface.OnClickListener() {
  30. public void onClick(DialogInterface dialog, int which) {
  31. tv.setText("取消刪除");
  32. }
  33. });
  34. //創建對話框
  35. AlertDialog ad = builder.create();
  36. //顯示對話框
  37. ad.show();
  38. }
  39. }
  40. );
  41. }
  42. }

main.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. >
  7. <TextView
  8. android:id="@+id/TextView_1"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="測試AlertDialog"
  12. />
  13. <Button
  14. android:id="@+id/Button_1"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:text="刪除文件"
  18. />
  19. </LinearLayout>

效果圖:

650) this.width=650;" height=120>

Copyright © Linux教程網 All Rights Reserved