<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<EditText
android:id="@+id/edt_test_one"
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="test"/>
<EditText
android:layout_marginTop="50dp"
android:layout_below="@id/edt_test_one"
android:id="@+id/edt_test_two"
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="test"/>
</RelativeLayout>
在使用EditText时,我们经常使用Android:hint = "***" 来设置EditText的输入提示,简单布局如上,其效果图如下:
如图:
可以看到我们通过hint这一属性设置了EditText的输入提示,如XML代码中设置的一样,显示为了test,但可以看到,EditText在获得焦点后,输入提示并没有消失,有时候我们希望EditText在获得焦点时隐藏输入提示,下面就来讲解怎么实现这一效果。
其实原理很简单,就是监听EditText的获取焦点事件,为EditText设置焦点变化监听器 OnFocusChangeListener,
重写其onFocusChange方法,处理相关逻辑即可,代码如下:
@Override
public void onFocusChange(View v,boolean hasFocus){
EditText textView = (EditText)v;
String hint = null;
switch (v.getId()) {
case R.id.edt_test_one:
if(hasFocus){
hint = v.getHint().toString();
v.setTag(hint);
v.setHint("");
}else{
</span>hint = v.getTag().toString();
v.setHint(hint);
}
break;
default:
break;
}
}
但还要注意一点,程序运行时第一个EditText貌似会自动获取焦点,那么用户可能就看不到你之前设置好的输入提示了,解决这个问题也不难,只需要给EditText控件所在的父布局设置两个属性即可。
分别为:
android:focusable="true"
android:focusableInTouchMode="true"
这样,程序运行时EditText就不会自动获取焦点,输入提示也就能正常显示了。
最后放出效果图: