[英]How to set default value for TextInputLayout in Android
I'm using the TextInputLayout
from Google's Material Design on Android.我在 Android 上使用Google Material Design中的
TextInputLayout
。 I want to set the default text value for the text field.我想为文本字段设置默认文本值。
I know I can set the hint, helper text, and error message, but I want to programatically set the default text value that in other cases would eventually be input by the user.我知道我可以设置提示、帮助文本和错误消息,但我想以编程方式设置在其他情况下最终将由用户输入的默认文本值。
According to the docs you can technically switch the inner TextInputEditText
to a regular EditText
but Google does not recommend doing this.根据文档,您可以在技术上将内部
TextInputEditText
切换为常规EditText
,但 Google 不建议这样做。 Should I explore the risks of doing that or is there a built-in solution I'm missing?我应该探索这样做的风险还是我缺少内置的解决方案?
You can use setText
method for TextInputEditTest as below where ever you want:您可以在任何地方使用
setText
方法进行TextInputEditTest如下所示:
textInputEditText.setText(R.string.yourStringName);//string from resources
textInputEditText.setText("yourString");//static string
If you want to set default text when your activity or fragment initialize You should use setText in onCreate method which is the first callback in activity and fragment life cycle.如果您想在活动或片段初始化时设置默认文本,您应该在onCreate方法中使用 setText,这是活动和片段生命周期中的第一个回调。
And the last thing: you can set default text for TextInputEditText not TextInputLayout because TextInputLayout extends from LinearLayout and therefore it doesn't have text property.最后一件事:您可以为TextInputEditText而不是TextInputLayout设置默认文本,因为 TextInputLayout 从 LinearLayout 扩展,因此它没有 text 属性。
Not really sure what your use case is, but you may think of one of the following:不太确定您的用例是什么,但您可能会想到以下其中一种:
Case 1: You want the user to see the default text案例 1:您希望用户看到默认文本
Case 2: User doesn't need to see the default text案例 2:用户不需要看到默认文本
If either of these cases don't work for you, please clarify the user experience you are seeking.如果这两种情况都不适合您,请说明您正在寻求的用户体验。 Eg, do you want to wait after a certain event/time to switch the hint with a default text?
例如,您是否想在某个事件/时间后等待以使用默认文本切换提示?
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/form_username">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.