如何从 Material Design TextInputLayout 中正确获取文本?

新手上路,请多包涵

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

我试着这样做:

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

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

原文由 Ziad H. 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 625
2 个回答

使用类似的东西:

 <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 的新实例,它不是 TextInputEditText 中的 TextInputLayout

原文由 Gabriele Mariotti 发布,翻译遵循 CC BY-SA 4.0 许可协议

就我而言,您不能只使用 String text = textInputLayout.getEditText().getText(); TextInputEditText 文本值。

您需要将其转换为 Editable 或使用 String.valueOf() 包装它,如果您要将其包装为 String ,如下所示:

XML

 <com.google.android.material.textfield.TextInputLayout
android:id="@+id/edt_title"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/request_title"
android:inputType="textCapWords"
android:maxLength="255" />
</com.google.android.material.textfield.TextInputLayout>

爪哇

TextInputLayout textInputLayout = findViewById(R.id.edt_title);

String strTitle = String.valueOf(textInputLayout.getEditText().getText());

要么

Editable strTitle = textInputLayout.getEditText().getText();

然后你可以像这样使用上面的字符串

Toast.makeText(YourClassName.this, strTitle, Toast.LENGTH_SHORT).show();

原文由 Muhammad Faisal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题