一、前言:
模拟点击事件主要用到第三方SDK中,我们获取不到页面子控件的点击事件 ,我们又想模拟点击,跳转到详情页面中,这时候使用模拟点击事件是最好不过的了。应用最多的比如说广告SDK。
二、使用:
1、MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/**
* btn点击按钮A
*/
btn.setOnClickListener {
clickByMistake()
}
/**
* 重写btn2的setOnTouchListener
*/
btn2.setOnTouchListener(OnTouchListener { v, event ->
val toast = Toast.makeText(
applicationContext,
"欢迎点击了我啊",
Toast.LENGTH_LONG
)
toast.show()
true
})
}
/**
* 执行模拟点击事件
*/
private fun clickByMistake() {
// Obtain MotionEvent object
val downTime = SystemClock.uptimeMillis()
val eventTime = SystemClock.uptimeMillis() + 100
val x = 0.0f
val y = 0.0f
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
val metaState = 0
val motionEvent = MotionEvent.obtain(
downTime,
eventTime,
MotionEvent.ACTION_UP,
x,
y,
metaState
)
//btn2发送触摸事件以查看
btn2.dispatchTouchEvent(motionEvent)
// 确保recycle方法只调用一次
motionEvent.recycle()
}
}
2、activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是第一个页面"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:textColor="#f00"
/>
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints"
android:text="点击按钮A"
/>
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints"
android:text="欢迎点击了我啊"
/>
</LinearLayout>
3、代码介绍:
1、点击btn的时候,调用clickByMistake()方法,里面重写btn2的dispatchTouchEvent方法(motionEvent)==》(相当于点击了btn2);
2、点击btn2,可以直接弹Toast;
4、参考大佬示例:
private fun setSimulateClick(view: View, x: Float, y: Float) {
var downTime = SystemClock.uptimeMillis()
val downEvent = MotionEvent.obtain(
downTime, downTime,
MotionEvent.ACTION_DOWN, x, y, 0
)
downTime += 1000;
val upEvent = MotionEvent.obtain(
downTime, downTime,
MotionEvent.ACTION_UP, x, y, 0
)
view.onTouchEvent(downEvent)
view.onTouchEvent(upEvent)
downEvent.recycle()
upEvent.recycle()
}