参考了网上的一些方法,实践之后可用,总结如下:
1.如何使EditText在进入Activity时不自动获取焦点
可在父布局上增加如下代码:
<span style="font-size:18px;"> android:focusableInTouchMode="true"</span>
网上说要增加两行代码,除此之外还要android:focusable="true",其实不必,因为即使设置android:focusable="false",也可以在进入界面时EditText不获取焦点,原因不太清楚,有知道的请指教!
下面是布局文件:<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:orientation="vertical" >
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:hint="请输入银行卡号" />
</LinearLayout>
2.如何在点击EditText控件外的区域使得EditText失去焦点?
只需要在MainAcitivity中找到EditText的父布局,这里是LinearLayout,如上设置了一个id。找到之后给LinearLayout设置setOnTouchListener请求焦点,则可以使得EditText失去焦点
private LinearLayout ll;
......
ll = (LinearLayout) findViewById(R.id.linear_layout);
ll.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ll.setFocusableInTouchMode(true);
ll.requestFocus();
return false;
}
});
因为布局文件中写过FocusableInTouchMode(true),所以这里可以不用加ll.setFocusableInTouchMode(true);如果没有写,则必须加上这行代码 ,使得LinearLayout在触摸模式下能获得焦点。requestFocus则是让其立马获得焦点
3.如何实现EditText的焦点监控事件处理
使用setOnFocusChangeListener方法
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
textView.setVisibility(View.VISIBLE);
}else{
textView.setVisibility(View.INVISIBLE);
}
}
});