22

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?

Abhimanyu
  • 11,351
  • 7
  • 51
  • 121
Bharat Kumar
  • 806
  • 14
  • 22
  • Also consider starring this issue about Compose-based date-/time-pickers to add your vote: https://issuetracker.google.com/issues/197942880 – Uli Mar 28 '22 at 19:41

1 Answers1

26

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.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841