jjin
jjin

Reputation: 13

How to call timePicker from a fragment?

I'm trying to change 12 hour - 24 hour mode from switch on Preference. But I can't find why val timepicker makes an error.

Please could anyone help me with correcting this? The full project is on https://github.com/illizien/Study-Aider

Thanks.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val timePicker = findViewById<TimePicker>(R.id.timePickerAtHeadsetPlugFragment)
        if(switchValue) {
            timePicker.setIs24HourView(true)
        } else {
            timePicker.setIs24HourView(false)
        }
    }

Upvotes: 0

Views: 162

Answers (1)

Florian T
Florian T

Reputation: 142

Use

import android.app.TimePickerDialog

You can call the dialog with

val myCalendar = Calendar.getInstance()

TimePickerDialog(context, { _: TimePicker?, hourOfDay: Int, minute: Int -> 
            // Do something with the time
}, myCalendar[Calendar.HOUR_OF_DAY], myCalendar[Calendar.MINUTE], true)
.show()

passing 'true' as the last argument sets the picker to 24 hour format, false would set it to 12 hour format. You can call this from a fragment or an activity.

Upvotes: 1

Related Questions