How to get text from material design TextInputLayout correctly?

19,336

Solution 1

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.

Solution 2

I had the same problem as you. I just solved it this way. In the String variable I need to validate that the data has been correctly inserted with .trim()

  String vname=Name.getEditText().getText().toString().trim();
Share:
19,336
Ziad H.
Author by

Ziad H.

Updated on June 23, 2022

Comments

  • Ziad H.
    Ziad H. almost 2 years

    I want to get a 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!!

  • LuckMan
    LuckMan over 3 years
    Is there a way to get/access the TextInputLayout of a TextInputEditText that's "inside" said TextInputLayout, something like editText.getTextInputLayout?
  • The incredible Jan
    The incredible Jan over 3 years
    getText() returns Editable. You have to call getText().toString(). I don't know why you use getEditText() on the Layout. I use the TextInputEditText directly: ((TextInputEditText)getView().findViewById(R.id.etTheText)).‌​getText().toString()‌​.
  • The incredible Jan
    The incredible Jan over 3 years
    You don't validate anything. You just trim your String.
  • Петр Воротинцев
    Петр Воротинцев almost 2 years
    In my case, I was using view input argument to OnClick() method. But, when I changed view.findViewById(R.id.input) to getView().findViewById(R.id.input_recipient) everything works like a charm. After that, I get my text with getView().findViewById(R.id.input_recipient).getText().toStr‌​ing().