Jetpack compose 中的 AppCompatActivity 而不是 ComponentActivity [英] AppCompatActivity instead of ComponentActivity in Jetpack compose

查看:158
本文介绍了Jetpack compose 中的 AppCompatActivity 而不是 ComponentActivity的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Jetpack compose 中单击按钮打开 datePicker 对话框.
为此,我在按钮的 onClick 操作中使用以下代码.

I want to open datePicker dialog on a button click in Jetpack compose.
For that, I am using the below code inside the button's onClick action.

val context = LocalContext.current
Button(onClick = {
    (context as AppCompatActivity).let {
        val picker = MaterialDatePicker.Builder.datePicker().build()
        picker.show(it.supportFragmentManager, picker.toString())
        picker.addOnPositiveButtonClickListener {
            // some code
        }
    }
})

如果我使用的是 ComponentActivity,则不支持 supportFragmentManager.
可以从 AppCompatActivity 扩展 Activity 吗?
或者有没有其他办法,如果上述解决方案不正确,我可以得到解决方案?

If I am using the ComponentActivity, supportFragmentManager is not supported.
Is it fine to extend the activity from AppCompatActivity?
Or is there any other way, I can get the solution if the above-mentioned solution is not correct?

推荐答案

您可以使用 AppCompatActivity 因为它扩展了 FragmentActivity 扩展了 ComponentActivity.

You can use the AppCompatActivity since it extends FragmentActivity which extends ComponentActivity.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
           val activity = LocalContext.current as AppCompatActivity
                Button(onClick={ showDatePicker(activity)}){
                Text("Picker")
           }
        }
    }
}

fun showDatePicker(activity: AppCompatActivity){
    val picker = MaterialDatePicker.Builder.datePicker().build()
    activity?.let {
        picker.show(it.supportFragmentManager, picker.toString())
        picker.addOnPositiveButtonClickListener {
        }
    }
}

注意:它至少需要 AppCompat 1.3.0 版本.

这篇关于Jetpack compose 中的 AppCompatActivity 而不是 ComponentActivity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆