如何使用 kotlin 在 android studio 中引用 timerPicker

How to reference a timerPicker in android studio using kotlin

当这个程序 运行s 在模拟器上工作时,但是,当我 运行 它在我的 phone 上时 timePicker 是引用为空。

模拟器 运行ning API 26 可以 运行 它很好,但是,在 API 28 它不起作用。所以我认为它可能与 API 28 相关(这也是我的 phone 运行s)

class MainActivity : AppCompatActivity() {

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

        val picker = findViewById<TimePicker>(R.id.timePicker)

        val t = picker == null // Is true on phone and is false on emulator

        Toast.makeText(this@MainActivity, t.toString(), Toast.LENGTH_LONG).show()
        //picker.setIs24HourView(true)

        val activity = findViewById<EditText>(R.id.activityName)
        val mCallApiButton = findViewById<Button>(R.id.submit)
        mCallApiButton?.setOnClickListener{
            val time = GetTime(picker)

            PostActivity(time, activity.text.toString()) // Function that does other stuff
        }
    }
}

我需要引用 timePicker 以便将其设置为 24 小时。

这里是布局文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent" app:layout_constraintTop_toTopOf="parent">
        <TimePicker android:id="@+id/timePicker"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:timePickerMode="clock"/>
        <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:id="@+id/activityName"
                android:singleLine="true" android:hint="Activity" android:textSize="18sp"
                android:textAlignment="center" android:autofillHints="Activity"/>
        <Button
                android:text="Submit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:id="@+id/submit"/>
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

模拟器的屏幕截图:(应该是这样的)

phone 的屏幕截图:

这是因为我使用 API 28 而不是 27 及以下。答案可以在这里找到: https://github.com/xamarin/Xamarin.Forms/issues/5159