android中focusable和focusableInTouchMode

首先先来说明这两个属性的区别,借鉴书上的一段文字:

大多数控件都可以获得焦点,也就是处在选中状态,如果android:focusable属性值为true,表示可以通过键盘(虚拟键盘或者物理键盘)或者轨迹球将焦点移动到当前控件上,如果该属性值为false,则无法将焦点移动到当前控件。

在默认情况下,触摸一个按钮虽然可以触发该控件的单机事件,但无法使控件处在焦点状态。而将andorid:focusableInTouchMode属性值设为true,当触摸某个控件时,会先将焦点移动到被触摸的控件上,然后需要在触摸该控件才会响应单击事件。但是要注意的是们需要将android:focusable属性值设为true,当前控件才可能获得焦点,否则当前控件无论使用何种方式都无法获得焦点。


例子:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#ddffff"
              android:gravity="center"
              android:orientation="vertical">

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_marginBottom="20dp" android:focusable="true"
            android:focusableInTouchMode="true"
            android:text="click me"/>

    <EditText android:layout_width="300" android:layout_height="wrap_content"
              android:hint="点击获取焦点"/>

</LinearLayout>


进入该页面时,因为button设置focusableInTouchMode为true,则一进入该页面时,先获得了焦点。这时可以先点击edittext,这时输入框获得焦点,并弹出输入法,这时候去点击button,会发现button获得焦点,而且你会发现button的外观也不一样,外面有一圈边框,显示已获得焦点的状态。当然此时输入框已失去焦点,没有光标。


但是如果button没有设置focusableInTouchMode的属性话,即使狂点,焦点还是在输入框上,光标依旧可见。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值