Jetpack Compose中如何给LazyColumn内的Text添加点击事件拨打电话
实现方案
前置配置
- 在
AndroidManifest.xml中添加拨号权限:
<uses-permission android:name="android.permission.CALL_PHONE" />
- 针对Android 6.0及以上系统,需要在进入当前页面前动态申请
CALL_PHONE权限,否则点击拨号会触发权限错误。
代码改造
修改逻辑如下:
- 改造拨号函数,支持传入指定号码,调用系统拨号能力
- 将显示文本和预设号码做映射绑定,避免重复编写Text组件代码
- 给Text组件添加点击触发拨号的逻辑
完整修改后代码:
import android.content.Intent import android.net.Uri import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp // 预设号码与显示文本的映射,可自行修改对应号码 private val contactList = listOf( "primero" to "13800000001", "segundo" to "13800000002", "tercero" to "13800000003" ) @Composable fun Hacerllamada(phoneNumber: String) { val context = LocalContext.current val intent = Intent(Intent.ACTION_CALL).apply { data = Uri.parse("tel:$phoneNumber") // 非Activity上下文启动Activity需要加该Flag addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } context.startActivity(intent) } @Preview @Composable fun Columna() { LazyColumn( modifier = Modifier .fillMaxSize() .background(Color.Gray) ) { items(contactList) { (displayText, phoneNumber) -> Text( text = displayText, fontSize = 32.sp, color = Color.White, modifier = Modifier .fillMaxWidth() .clickable { Hacerllamada(phoneNumber) }, textAlign = TextAlign.Center ) } } }
可选优化
如果不需要点击后直接拨打,仅需跳转到系统拨号页预填号码,可以把Intent.ACTION_CALL替换为Intent.ACTION_DIAL,这种场景不需要申请CALL_PHONE权限。
内容的提问来源于stack exchange,提问作者LEMILEMI
相关产品推荐
相关产品推荐

