如何在Android中创建文本输入对话框?

4

如何在Android上创建最佳的模态文本输入对话框?

我希望阻塞直到用户输入文本并点击确定按钮,然后从对话框中提取文本,就像awt中的模态对话框一样。

谢谢!


你的意思是输入框类型? - Lucifer
3个回答

7

试试这个:

final Dialog commentDialog = new Dialog(this);
commentDialog.setContentView(R.layout.reply);
Button okBtn = (Button) commentDialog.findViewById(R.id.ok);
okBtn.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                    //do anything you want here before close the dialog
                                    commentDialog.dismiss();
                            }
 });
Button cancelBtn = (Button) commentDialog.findViewById(R.id.cancel);
cancelBtn.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                    commentDialog.dismiss();
                            }
 });

reply.xml

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

    <EditText android:layout_width="fill_parent"
            android:layout_gravity="center" android:layout_height="wrap_content"
            android:hint="@string/your_comment" android:id="@+id/body" android:textColor="#000000"
            android:lines="3" />
    <LinearLayout android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <Button android:id="@+id/ok" android:layout_height="wrap_content"
                    android:layout_width="wrap_content" android:text="@string/send"  android:layout_weight="1"
                     />
            <Button android:id="@+id/cancel" android:layout_height="wrap_content"
                    android:layout_width="wrap_content"  android:layout_weight="1"
                    android:text="@android:string/cancel" />
    </LinearLayout>
</LinearLayout>

4
将此代码添加以显示对话框。 commentDialog.show(); - Sahil
为什么它的样式与其他部分不一样? - FtheBuilder

2
你可以使用XML布局创建自定义对话框。如果你想阻止用户输入文本和点击确定按钮之前离开,可以使用setCancelable(false)
检查谷歌搜索链接:带EditText的对话框

setCancelable(false)只是表面上的吗?我的意思是它真的可以暂停一切吗?在我的应用程序中,我希望在对话框后面收集数据的活动被暂停。 - Sibbs Gambling

1

我想你的意思是模态对话框。

我会建议看一下AlertDialog.Builder,作为一个起点,更新的做法是使用DialogFragment,这样可以更好地控制对话框的生命周期。

你需要找的关键方法是dialog.setCancelable(false);


setCancelable(false)只是表面上的吗?我的意思是它真的可以暂停一切吗?在我的应用程序中,我希望在对话框后面收集数据的活动被暂停。也就是说,数据收集会在用户关闭对话框之前停止。这样做可以实现吗? - Sibbs Gambling
@perfectionming 我认为你需要开一个新的问题。 - Chris.Jenkins
1
@perfectionm1ng,您需要通过自己的代码暂停“所有内容”。因为这个模态对话框无法为您完成此操作。也许您可以在调用show()对话框之前暂停数据收集。 - Ngo Phuong Le

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接