Search code examples
androidmaterial-designandroid-textinputlayoutandroid-textinputedittext

How to get text from material design TextInputLayout correctly?


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!!


Solution

  • 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.