如何正确地从材质设计TextInputLayout中获取文本? [英] How to get text from material design TextInputLayout correctly?

查看:92
本文介绍了如何正确地从材质设计TextInputLayout中获取文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用自定义的结束图标从材质设计的TextInputLayout中获取文本.

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

我试图这样做:

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

但是我得到一个空文本,不是null而是空的!

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

推荐答案

使用类似的方法:

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

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

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

只需使用:

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

您的问题在这里:

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

您只是在创建 TextInputEditText 的新实例,它不是 TextInputLayout 中的 TextInputEditText .

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

这篇关于如何正确地从材质设计TextInputLayout中获取文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆