InputTextLayout не может корректно выполнить getText (). ToString () из своего EditText - PullRequest
0 голосов
/ 20 января 2019

Я сейчас пишу метод AlertDialog, который генерирует пользовательский AlertDialog, состоящий из TextView и InputTextLayout (weight_InputLayout) для пользователей, чтобы ввести некоторое число.

Однако после того, как я проверил свой метод AlertDialog, я обнаружил, что, хотя мой AlertDialog может успешно отображаться, я не могу получить содержимое в EditText должным образом, и он всегда возвращает пустую строку, поэтому он всегда выдает исключение NumberFormatException.

Я добавил достаточно журнала в мою программу, и результат журнала выглядит следующим образом

V/userweightBtn: Showing the dialog for user
V/setWeightDialog: weight_InputLayout is not null
E/setWeightDialog: text is not null
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@35e561b 
time:527753839
V/setWeightDialog: user clicked the button
V/weight: 50
V/setWeightDialog: User input is valid.
V/setWeightDialog: User's input has been saved

и ниже - мои коды для метода AlertDialog, обратите внимание, что вес = 50 - это фиктивное число, которое я должен проверять для других функций, поэтому не нужно об этом думать:

//create a dialog which lets user enter weight data
private AlertDialog setWeightDialog()
{


    LayoutInflater LI = LayoutInflater.from(MainActivity.this);
    View v =LI.inflate(R.layout.weight_dialog,null);

    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setCancelable(false);
    builder.setView(R.layout.weight_dialog);
    weight_InputLayout = v.findViewById(R.id.userWeightLayout);
    if (weight_InputLayout == null)
        Log.e("setWeightDialog","null weight_InputLayout");
    else
    {
        Log.v("setWeightDialog","weight_InputLayout is not null");
        EditText text = weight_InputLayout.getEditText();
        if (text == null)
            Log.v("setWeightDialog","text is null");
        else Log.e("setWeightDialog","text is not null");
    }
    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
                Log.v("setWeightDialog","user clicked the button");
                String inputted_weight = weight_InputLayout.getEditText().getText().toString();
                Log.e("inputted_weight",inputted_weight);
                int weight = 50;//A dummy number which enables further test.
                //weight = Integer.parseInt(inputted_weight); this is what i want
                Log.v("weight",String.valueOf(weight));
                try
                {
                    if (weight > 0)
                    {
                        Log.v("setWeightDialog","User input is valid.");
                        //If weight input is valid, then save into preferences.
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.clear();
                        editor.putInt(getString(R.string.UserWeight),weight);
                        editor.apply();//test: apply or commit?
                        Log.v("setWeightDialog","User's input has been saved");
                        //after saving, dismiss the dialog.
                        builder.create().dismiss();
                    } else
                    {
                        Log.e("setWeightDialog","User input is INVALID");
                        weight_InputLayout.getEditText().setText("");
                        weight_InputLayout.getEditText().setHint(getString(R.string.invalid_weight));
                    }
                } catch (Exception e)
                {
                    Log.e("setWeightDialog","Error in saving user's weight",e);
                }
        }
    });

    return builder.create();
}

Макет weight_dialog состоит только из TextView и InputTextLayout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/weight_dialogLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/weight_prompt"
    android:layout_width="339dp"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="15dp"
    android:layout_marginTop="40dp"
    android:text="@string/enter_Weight"
    android:textSize="24sp" />

<android.support.design.widget.TextInputLayout
    android:id="@+id/userWeightLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/weight_prompt">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/userWeightEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number" />
</android.support.design.widget.TextInputLayout>

</RelativeLayout>

Я ожидал, что строка "inputted_weight" может получить строку, введенную в inputTextLayout пользователями. Однако эти коды -

            String inputted_weight = weight_InputLayout.getEditText().getText().toString();
            Log.e("inputted_weight",inputted_weight);

просто опускаются моим приложением.

1 Ответ

0 голосов
/ 20 января 2019

Вы можете попробовать взять текст TextInputEditText непосредственно из id: userWeightEditText вместо textlayout получить edittext.

например:

String text = findViewbyid (R.id.userWeightEditText) .getText (). ToString ()

...