Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 自定義對話框:把任意佈局塞進 AlertDialog

系統預設的 AlertDialog 只能顯示文字與固定按鈕,一旦需求變成「輸入名稱後再確定」,就必須自己動手客製。以下示範如何把自訂的 XML 佈局放進對話框中,並在按下確定時讀取輸入內容。

CustomDialogActivity.java

package wzhnsc.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CustomDialogActivity extends Activity {

    private Button custom = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        custom = (Button) this.findViewById(R.id.custom);
        custom.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                showCustomDia();
            }
        });
    }

    private void showCustomDia() {
        AlertDialog.Builder customDia = new AlertDialog.Builder(CustomDialogActivity.this);
        final View viewDia = LayoutInflater.from(CustomDialogActivity.this)
                                             .inflate(R.layout.custom_dialog, null);
        customDia.setTitle("新建文件夾");
        customDia.setView(viewDia);
        customDia.setPositiveButton("確定", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                EditText diaInput = (EditText) viewDia.findViewById(R.id.file_name);
            }
        });
        customDia.create().show();
    }
}

整段程式的關鍵只有兩行:LayoutInflater.inflate() 把你的佈局變成 View,再用 setView() 交給 Builder。之後所有 findViewById 都要在這個 viewDia 上做,而不是在 Activity 上找,這是最常犯的錯誤。

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/custom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自定義對話框" />

</LinearLayout>

custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="請輸入名字:" >
    </TextView>
    <EditText android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/file_name"
        android:lines="1">
    </EditText>
</LinearLayout>

想再往前一步的話,可以在 setPositiveButton 的回呼裡把 diaInput.getText() 取出來做驗證或寫入檔案;若要提供取消行為,再串上 setNegativeButton 即可。

Copyright © Linux教程網 All Rights Reserved