android中focusable和focusableInTouchMode

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

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

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

例子:

 
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

  2. android:layout_width="match_parent"

  3. android:layout_height="match_parent"

  4. android:background="#ddffff"

  5. android:gravity="center"

    扫描二维码关注公众号,回复: 2816676 查看本文章
  6. android:orientation="vertical">

  7.  
  8. <Button android:layout_width="wrap_content" android:layout_height="wrap_content"

  9. android:layout_marginBottom="20dp" android:focusable="true"

  10. android:focusableInTouchMode="true"

  11. android:text="click me"/>

  12.  
  13. <EditText android:layout_width="300" android:layout_height="wrap_content"

  14. android:hint="点击获取焦点"/>

  15.  
  16. </LinearLayout>


 

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

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

猜你喜欢

转载自blog.csdn.net/qq_41405257/article/details/81709707
今日推荐