How to get text from material design TextInputLayout correctly?

Ziad H. picture Ziad H. · Sep 5, 2019 · Viewed 12.9k times · Source

I want to get text from the material design's TextInputLayout using a custom end Icon.

I tried to do that:

TextInputLayout textInputCustomEndIcon = findViewById(R.id.editText);
final TextInputEditText editText = new TextInputEditText(textInputCustomEndIcon.getContext());

textInputCustomEndIcon
                .setEndIconOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (editText.getText() != null) {
                                    String text = editText.getText().toString();

                                    Log.i("MainActivity", "setEndIconOnClickListener:"+ text);
                                }
                            }
                            });

But I get an empty text, not null but empty!!

Answer

Gabriele Mariotti picture Gabriele Mariotti · Sep 5, 2019

Using something like that:

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/custom_end_icon"
    ...>

    <com.google.android.material.textfield.TextInputEditText
       ../>

</com.google.android.material.textfield.TextInputLayout>

Just use:

TextInputLayout textInputLayout = findViewById(R.id.custom_end_icon);
String text = textInputLayout.getEditText().getText();

Your issue is here:

final TextInputEditText editText = new TextInputEditText(textInputCustomEndIcon.getContext());

You are only creating a new instance of TextInputEditText, it isn't the TextInputEditText inside the TextInputLayout.