Compose 小功能记录---TextField自动弹出键盘

开发中时常有搜索页的功能, 要求进入页面输入框自动获取光标并弹出软键盘. EditText的实现已经很成熟了, Compose如何实现呢? 先看下效果

效果

compose-input.gif

代码

val focusRequester = remember { FocusRequester() } //焦点
val softKeyboard = LocalSoftwareKeyboardController.current //软键盘

LaunchedEffect(Unit) {
    delay(100) //延迟操作(关键点)
    focusRequester.requestFocus()
    softKeyboard?.show()
}


CustomTextField(
    hint = "请输入关键字",
    modifier = Modifier
        .focusRequester(focusRequester)
        .background(
            color_form_enable,
            shape = RoundedCornerShape(4.dp)
        )
        .height(40.dp)
        .padding(start = 10.dp)
        .weight(1f), text = ccc, leadingIcon = {
        Icon(
            modifier = Modifier.size(20.dp),
            painter = painterResource(id = R.drawable.ic_baseline_search_24),
            contentDescription = null
        )
    },
    maxLines = 1,
    onTextChange = {
        mViewModel.filterKeyword(this)
    }
)

分析

主要是 FocusRequesterLocalSoftwareKeyboardController 获取焦点和软键盘.
页面初始化的时候启动协程执行 requestFocus()show() 的操作.

关键点是: delay(100) 协程的延迟操作, 主要是延迟执行 softKeyboardshow().

这样想要的效果就实现了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值