3

我正在尝试在单个类中创建自定义对话框。该对话框在主活动中启动:

        DialogLogin login = new DialogLogin();
        login.show(getFragmentManager(), DISPLAY_SERVICE);

在启动应用程序时,主要活动在后台启动,然后对话框启动。在对话框中有一个 EditText 字段来接收用户输入。按下保存按钮时,应读出 EditText 字段并显示输入,但它始终为空。此外,LogCat 中没有错误...我尝试了许多相同问题的解决方案,但没有任何效果。我希望任何人都有一个可行的解决方案!=)

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;

public class DialogLogin extends DialogFragment {
String androidID;
LayoutInflater inflater;

public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    inflater = getActivity().getLayoutInflater();

    builder.setMessage(R.string.loginMessage)
            .setTitle(R.string.login)
            .setView(inflater.inflate(R.layout.loginlayout, null))
            .setPositiveButton(R.string.speichern,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            System.out.println("LOGIN");
                            View v = inflater.inflate(R.layout.loginlayout, null);
                            EditText text = (EditText) v.findViewById(R.id.loginEdit);

                            System.out.println(text.getText().toString()); //Displays nothing
                            System.out.println(text.length());              //is 0

                        }
                    });

    return builder.create();
}

}

和 loginlayout.xml:

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

<EditText
    android:id="@+id/loginEdit"
    android:inputType="text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="@string/editText" >

</EditText>

</LinearLayout>
4

1 回答 1

6

You are inflating a new layout, where the EditText has no text in it. You'll need to only once inflate your layout, and keep a reference to it.

final View view = inflater.inflate(R.layout.loginlayout, null);

/* ... */
.setView(view)
/* ... */
EditText text = (EditText) view.findViewById(R.id.loginEdit);
于 2013-07-04T16:59:27.563 回答