EditText焦点问题探讨

参考了网上的一些方法,实践之后可用,总结如下:

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);
				}
			}
		});



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值