Android 中的 performClick 方法
点击 button2 时 button1 的点击回调也会执行,同时界面上也会呈现被点击的效果(如水波纹)
class MyActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val layout = LinearLayout(this)
layout.orientation = LinearLayout.VERTICAL
val button1 = Button(this).apply {
text = "button1"
setOnClickListener {
println("button1 clicked.")
}
}
val button2 = Button(this).apply {
text = "button2"
setOnClickListener {
button1.performClick()
}
}
layout.apply {
addView(button1)
addView(button2)
}
}
}
Jetpack Compose 中的实现
算是折中实现吧,也许还有更好的方法
@Composable
@Preview
fun App() {
MaterialTheme {
val state = rememberScrollState()
Column(modifier = Modifier.padding(16.dp).verticalScroll(state)) {
val interactionSource = remember {
MutableInteractionSource()
}
val block = {
println("button1 clicked.")
}
Button(onClick = {
block()
}, interactionSource = interactionSource) {
Text("button1")
}
Button(onClick = {
val press = PressInteraction.Press(Offset.Zero)
interactionSource.tryEmit(press)
val release = PressInteraction.Release(press)
interactionSource.tryEmit(release)
block()
}) {
Text("button2")
}
}
}
}
场景
乍一看可能觉得没什么用,主要用于如下场景:
Jetpack Compose for Desktop 中,界面上有一个输入框和一个提交按钮,用户光标位于输入框中,输入完成后敲回车键,希望能触发提交操作,相当于手动点击了提交按钮,这时可能就需要用到上面的方法了。
网友评论