我想设置时间码的初始值

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TimePicker
import androidx.annotation.RequiresApi


class MainActivity : AppCompatActivity() {
@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    var periodTimePiker: TimePicker = findViewById(R.id.period_timePicker)
    periodTimePiker.setIs24HourView(true)
    periodTimePiker.hour = 10
    periodTimePiker.minute = 10

}
}

和xml
 <TimePicker
            android:id="@+id/period_timePicker"
            android:layout_width="291dp"
            android:layout_height="137dp"
            android:layout_gravity="center_vertical"
            android:timePickerMode="spinner" />
        />

当使用periodTimePiker.hour = 10时
periodTimePiker.minute = 10
申请停止

android sy崩溃
 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.test.appTest, PID: 10550
java.lang.NoSuchMethodError: android.widget.TimePicker.setHour
    at com.test.appTest.MainActivity.onCreate(MainActivity.kt:20)
    at android.app.Activity.performCreate(Activity.java:5264)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1099)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1266)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5421)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:979)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
    at dalvik.system.NativeStart.main(Native Method)

我尝试了periodTimePiker.hour和setHour

最佳答案

setHoursetMinute RequiresApi是API23。您可能在较低版本上运行它,这就是它崩溃的原因。您可以对较低版本使用不推荐使用的方法。

    periodTimePiker.setIs24HourView(true)
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
        periodTimePiker.hour=5
        periodTimePiker.minute=16
    }else{
        periodTimePiker.currentHour=5
        periodTimePiker.currentMinute=16
    }

07-27 15:45