Android 代码实现模拟点击

2023-12-29 11:26:15

废话不多说,直接上代码,自己修改点击范围

private fun preFromClick() {
        mBinding.root.postDelayed({
            val sw: Int = this.requireActivity().resources.displayMetrics.widthPixels
            val sh: Int = this.requireActivity().resources.displayMetrics.heightPixels
            val x = (sw.toDouble() - sw.toDouble() * 0.5).toInt()
            val y = (sh.toDouble() - sh.toDouble() * 0.5).toInt()
            preFromClick(this.requireActivity(), x, y)
        },150)
    }

    private fun preFromClick(activity: Activity?, x: Int, y: Int) {
        if (activity != null) {
            val evenDown = MotionEvent.obtain(
                System.currentTimeMillis(),
                System.currentTimeMillis() + 100L,
                0,
                x.toFloat(),
                y.toFloat(),
                0
            )
            val eventUp = MotionEvent.obtain(
                System.currentTimeMillis(),
                System.currentTimeMillis() + 100L,
                1,
                x.toFloat(),
                y.toFloat(),
                0
            )
            evenDown.recycle()
            eventUp.recycle()
            activity.dispatchTouchEvent(evenDown)
            activity.dispatchTouchEvent(eventUp)
        }
    }

puivate fun dp2px(Context context, int dp) : Int {
        val metrics = requireActivity().resources.displayMetrics
        return (int)((float)dp * ((float)metrics.densityDpi / 160.0F));
    }

文章来源:https://blog.csdn.net/Steve_XiaoHai/article/details/135284144
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。