How to pick a second using TimePicker, android

后端 未结 6 1148
长发绾君心
长发绾君心 2021-02-07 05:51

I have used TimePicker to make the user to choose time see here and here also. But I didnot find a way to make the user to select second also. Now user can select Hour and Minut

6条回答
  •  伪装坚强ぢ
    2021-02-07 06:05

    I wrote a Kotlin extension function to do this. It's messy but it gets the job done:

    /**
     * Adds seconds number picker into the [TimePicker] format programmatically.
     * */
    fun TimePicker.addSeconds() {
        val system = Resources.getSystem()
        val idHour = system.getIdentifier("hour", "id", "android")
        val idMinute = system.getIdentifier("minute", "id", "android")
        val idAmPm = system.getIdentifier("amPm", "id", "android")
        val idLayout = system.getIdentifier("timePickerLayout", "id", "android")
        val spinnerHour = findViewById(idHour) as NumberPicker
        val spinnerMinute = findViewById(idMinute) as NumberPicker
        val spinnerAmPm = findViewById(idAmPm) as NumberPicker
        val outerLayout = findViewById(idLayout) as LinearLayout
        val layout = outerLayout.getChildAt(0) as LinearLayout
        layout.removeAllViews()
        (spinnerAmPm.parent as ViewGroup).removeView(spinnerAmPm)
    
        layout.addView(spinnerHour)
        setImeOptions(spinnerHour, 0)
        layout.addView(spinnerMinute)
        setImeOptions(spinnerMinute, 1)
    
        val spinnerSecond = createSecondPicker(spinnerHour.context)
        layout.addView(spinnerSecond)
        setImeOptions(spinnerAmPm, 2)
        val params = spinnerHour.layoutParams
        spinnerSecond.layoutParams = params
    
        layout.addView(spinnerAmPm)
        setImeOptions(spinnerAmPm, 3)
    }
    
    private fun createSecondPicker(context: Context): NumberPicker {
        val spinnerSecond = NumberPicker(context)
        spinnerSecond.id = R.id.second
        spinnerSecond.setFormatter { i -> String.format("%02d", i) }
        spinnerSecond.minValue = 0
        spinnerSecond.maxValue = 59
        return spinnerSecond
    }
    

    You'll also need to add this id to res/values/ids.xml so that you can reference the seconds field programmatically using R.id.second

    
    

    Shoutout to this post for the idea: https://stackoverflow.com/a/60601077/1709354

提交回复
热议问题