个人技术分享

我们很多时候会对某些View设置点击事件,但是,当对这个View同时设置了focusableInTouchMode=true时,第一次点击事件会被消费为为此View获取焦点。

<View
   	android:id="@+id/v_click"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:focusableInTouchMode="true"
    android:background="@color/cardview_dark_background"
    />

创建一个View,并同时指定了 android:focusableInTouchMode="true",在Activity代码中对View设置点击事件。

var count = 0

findViewById<View>(R.id.v_click)?.let {
     it.setOnFocusChangeListener { v, hasFocus -> Log.e("V_CLICK", "hasFocus  ${hasFocus}") }
     it.setOnClickListener {
         Log.e("V_CLICK", "click ${++count}")
     }
 }

发现第一次点击,LogCat显示:

V_CLICK  E  hasFocus  true

再次点击,才出现点击事件的Log:

V_CLICK  E  click 1