Android can't get EditText getText().toString(

2019-02-18 23:09发布

I'm trying to create a custom Dialog in an individual class. The dialog is started in the main activity:

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

On starting the application the main activity starts in the background and then the dialog starts. In the dialog there is an EditText-field to receive user-input. On pressing the save-button the EditText-field should be read-out and the input displayed, but it's always empty. Moreover there are no errors in the LogCat... I tried many solutions of the same problem, but nothing worked. I hope anyone has a working solution ! =)

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();
}

}

And the 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>

1条回答
够拽才男人
2楼-- · 2019-02-18 23:48

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);
查看更多
登录 后发表回答