Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppCompatActivity instead of ComponentActivity in Jetpack compose

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
        }
    }
})

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?

like image 487
Bharat Kumar Avatar asked May 03 '21 06:05

Bharat Kumar


People also ask

What is LazyColumn in jetpack compose?

A LazyColumn is a vertically scrolling list that only composes and lays out the currently visible items. It's similar to a Recyclerview in the classic Android View system.

What is mutableStateOf jetpack compose?

mutableStateOf creates an observable MutableState<T> , which is an observable type integrated with the compose runtime. Any changes to value will schedule recomposition of any composable functions that read value . In the case of ExpandingCard , whenever expanded changes, it causes ExpandingCard to be recomposed.

Does jetpack compose use RecyclerView?

RecyclerView 1.3. 0-alpha02 and Compose UI 1.2. 0-beta02 bring out-of-the-box performant usage of composables from RecyclerView — no extra code required!

Can you use Java with jetpack compose?

Can I use it with Java? Jetpack Compose is Kotlin exclusive. It uses features such as coroutines, and the handling of @Composable annotations is done by a Kotlin compiler. There is no way to get access to these from Java.


1 Answers

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 {
        }
    }
}

Note: it requires at least the AppCompat 1.3.0 version.

like image 98
Gabriele Mariotti Avatar answered Sep 22 '22 13:09

Gabriele Mariotti