java 第一个焦点上的 EditText 清除文本 - Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13022501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
EditText clear text on first focus - Android
提问by Matan Kadosh
I have few EditText objects with text inside. I want that on the first time an EditText is getting focus to delete the text in it, but only on the first time.
我有几个带有文本的 EditText 对象。我希望在 EditText 第一次获得焦点以删除其中的文本时,但仅限于第一次。
How can i do it?
我该怎么做?
Here's an example: I have an EditText called SomeThing with the text "someText" in it. when the user touches SomeThing for the first time i want the "someText" to be deleted. so let's say the text was deleted and now the user typed in his own text, this time "someOtherText", and the EditText lost focus for some other EditText. This time when the user will tap SomeThing, "someOtherText" won't get deleted because that's the second time it get's focus.
这是一个示例:我有一个名为 SomeThing 的 EditText,其中包含文本“someText”。当用户第一次触摸 SomeThing 时,我希望删除“someText”。所以假设文本被删除,现在用户输入了他自己的文本,这次是“someOtherText”,而 EditText 失去了其他一些 EditText 的焦点。这次当用户点击 SomeThing 时,“someOtherText”不会被删除,因为这是它第二次获得焦点。
回答by Soham
Matan, I am not sure if this is what you are looking at, but I think you want to display a 'hint'for your Edit Text
Matan,我不确定这是否是您正在查看的内容,但我认为您想为您的编辑文本显示“提示”
Example
例子
<EditText
.
.
android:hint="Please enter your name here">
For an example check this http://www.giantflyingsaucer.com/blog/wp-content/uploads/2010/08/android-edittext-example-3a.jpg
例如检查这个http://www.giantflyingsaucer.com/blog/wp-content/uploads/2010/08/android-edittext-example-3a.jpg
回答by LazarusX
If you are looking for a way to add placeholder for the EditText
, just add android:hint = 'some text'
to the corresponding XML file or call the setHint('some text')
method on the EditText
.
如果你正在寻找一种方式来添加的占位符EditText
,只需添加android:hint = 'some text'
到相应的XML文件或调用setHint('some text')
的方法EditText
。
Otherwise, you can use the OnFocusChangeListener()
to respond to the get focused event. To check if it is the first time for the EditText
to get focused, use another Boolean
variable (e.g., isFirstTimeGetFocused
) and initialized it to true
in onCreate()
method. After the EditText
gets focused, set isFirstTimeGetFocused
to false
;
否则,您可以使用OnFocusChangeListener()
来响应获取焦点事件。要检查 是否是第一次EditText
获得焦点,请使用另一个Boolean
变量(例如isFirstTimeGetFocused
)并将其初始化为true
inonCreate()
方法。在之后EditText
被聚焦,设置isFirstTimeGetFocused
到false
;
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus && isFirstTimeGetFocused){
editText.setText("");
isFirstTimeGetFocused = false;
}
});