如何在 Android 中动态或静态设置文本字段属性



如何在Android中为文本字段设置以下两个属性:

属性 1)如何设置包含"输入数字"等文本的文本字段,但单击该文本字段时,文本字段会自动变为空?

属性:2)假设我的应用程序中有两个文本字段。我的第一个文本字段只接受整数,第二个文本字段接受"名称、地址"等文本。但是我错误地在我的第一个文本字段中输入了一些文本,例如"苹果"或"球",该文本仅接受数字。

如何设置我的第一个文本字段,

以便当我单击第二个文本字段时,我的第一个文本字段应该显示一条 Toast 消息或更改输入数据的颜色以指示无效输入?

对于您的第一个问题...

我如何设置一个包含"输入数字"之类的文本的文本字段,但是当我们单击文本字段时,文本应该会自动从文本字段中删除变为空。

您正在寻找 EditText 视图具有的提示属性。在此处阅读更多内容: http://developer.android.com/reference/android/widget/TextView.html#attr_android:hint

对于第二个问题,你不需要经历所有的麻烦。只需为 EditText 设置 inputType 属性。这将强制键盘(虚拟或物理)仅使用字符串或数字,具体取决于您指定的输入类型。在此处阅读更多内容: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

属性 1) 您可以通过在 EditText 中添加 ht 来执行此操作:

<EditText
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:hint="Your text here"
 />

属性 2)对于名称:

  <EditText
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:hint="Your text here"
                        android:inputType="textPersonName"
     />

对于数字:

<EditText
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:hint="Your text here"
                        android:inputType="number"
     />

查看此处的所有参数。

查看第 2 期的 setError() 方法。