Android開發 相容焦點,觸控的點選
阿新 • • 發佈:2022-03-31
前言
解決痛點在設定 android:focusableInTouchMode="true" 後,用觸控點選不需要點選2次,關鍵是 isInTouchMode
程式碼
package com.lwlx.factorytest.expand \import android.util.Log import android.view.View private var clickInterval = 400L private var lastTime = 0L fun View.setOnIntervalClickListener(onIntervalClickListener: (View)-> Unit) { this.setOnClickListener { if (System.currentTimeMillis() - lastTime > clickInterval) { lastTime = System.currentTimeMillis() onIntervalClickListener.invoke(it) } } } /** * 設定焦點放大 */ fun View.setFocusEnlarge() { this.setOnFocusChangeListener { view, b -> if(b) { this.scaleX = 1.1f this.scaleY = 1.1f } else { this.scaleX = 1.0f this.scaleY = 1.0f } } } private var assistRequestFocusInterval = 400L private var assistRequestFocusLastTime = 0L /** * 輔助獲取焦點,防止獲取焦點後立即執行點選 */ fun View.assistRequestFocus(){ assistRequestFocusLastTime= System.currentTimeMillis() this.requestFocus() } /** * 設定焦點放大並且加邊框 */ fun View.setFocusEnlargeFrame(res:Int) { this.setOnFocusChangeListener { view, b -> if (b && this.isInTouchMode && System.currentTimeMillis() - assistRequestFocusLastTime > assistRequestFocusInterval){ Log.e("zh", ":performClick ") assistRequestFocusLastTime = System.currentTimeMillis() this.performClick() } if (b) { this.setBackgroundResource(res) this.setPadding(1,1,1,1) this.scaleX = 1.1f this.scaleY = 1.1f } else { this.setBackgroundResource(android.R.color.transparent) this.setPadding(0,0,0,0) this.scaleX = 1.0f this.scaleY = 1.0f } } } /** * 設定焦點放大並且加邊框,並且加點選 */ fun View.setFocusEnlargeFrameAndClick(res:Int, onIntervalClickListener: (View) -> Unit) { setOnIntervalClickListener(onIntervalClickListener) this.setOnFocusChangeListener { view, b -> if (b && this.isInTouchMode && System.currentTimeMillis() - assistRequestFocusLastTime > assistRequestFocusInterval){ Log.e("zh", ":performClick ") assistRequestFocusLastTime = System.currentTimeMillis() this.performClick() } if (b) { this.setBackgroundResource(res) this.setPadding(1,1,1,1) this.scaleX = 1.1f this.scaleY = 1.1f } else { this.setBackgroundResource(android.R.color.transparent) this.setPadding(0,0,0,0) this.scaleX = 1.0f this.scaleY = 1.0f } } }
Fragment中獲取焦點
public class BaseFragment extends com.lwlx.common.base.BaseFragment { public boolean mIsGetTheFocus = false; @Override public void onResume() { super.onResume(); mIsGetTheFocus = false; } public void setFocus(){ if (!mIsGetTheFocus){ mIsGetTheFocus = true; if (getView() != null){ getView().requestFocus(); } } } }
activity裡
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK){ return true } if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){ (supportFragmentManager.fragments[mBinding.viewPage.currentItem] as BaseFragment).setFocus() return true } return super.onKeyUp(keyCode, event) }
End