Jetpack Compose 组件androidx.compose.material3.Button点击和长按同时监听代码示例
时间: 2024-05-14 08:15:38 浏览: 210
Jetpack-Compose-Playground:Jetpack Compose示例代码和教程的社区驱动集合https://foso.github.iocompose
好的,关于Jetpack Compose 组件androidx.compose.material3.Button点击和长按同时监听代码示例,可以参考以下示例代码:
```
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapAndLongPress
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.myapp.viewmodel.CounterViewModel
import kotlinx.coroutines.launch
@ExperimentalFoundationApi
@Composable
fun ButtonClickListener() {
val scaffoldState = rememberScaffoldState()
var counterViewModel = viewModel<CounterViewModel>()
Scaffold(
scaffoldState = scaffoldState,
modifier = Modifier.fillMaxSize(),
content = {
Column(
modifier = Modifier
.padding(top = 10.dp, start = 16.dp, end = 16.dp)
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "点击或长按按钮可触发计数")
Spacer(modifier = Modifier.height(16.dp))
MyButton(
onClick = { counterViewModel.incrementCount() },
onLongClick = { counterViewModel.decrementCount() }
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "当前计数:${counterViewModel.count}",
style = MaterialTheme.typography.h4
)
}
},
bottomBar = {
BottomAppBar(cutoutShape = RoundedCornerShape(topStart = 16.dp)) {
IconButton(onClick = { }) {
Icon(Icons.Default.Save, contentDescription = "Save")
}
Spacer(Modifier.weight(1f, true))
IconButton(onClick = { }) {
Icon(Icons.Default.Share, contentDescription = "Share")
}
}
}
)
}
@ExperimentalFoundationApi
@Composable
fun MyButton(onClick: () -> Unit, onLongClick: () -> Unit) {
Surface(
modifier = Modifier
.padding(16.dp)
.pointerInput(Unit) {
detectTapAndLongPress(onLongClick = onLongClick, onTap = onClick)
},
shape = MaterialTheme.shapes.small,
color = MaterialTheme.colors.primary
) {
Text(
text = "Click or long press me",
style = MaterialTheme.typography.button,
color = Color.White,
modifier = Modifier.padding(
start = 16.dp,
top = 8.dp,
end = 16.dp,
bottom = 8.dp
)
)
}
}
```
这个示例使用了一个自定义的 MyButton 组件,通过 pointerInput() 来同时监听点击和长按事件,并在这两种事件发生时调用不同的回调函数。
另外,这个示例还使用了 Jetpack Compose 中的一些组件,如 Scaffold、Column、Text、BottomAppBar 等,并结合了 ViewModel 来管理计数器的状态,实现了点击或长按按钮可触发计数的效果。
希望这个示例能够对你有所帮助。
阅读全文