我是编程新手,我被 Android 功能困住了。 我有一个 float 操作按钮,我试图用它来打开日期选择器对话框,但我收到一个异常,其中显示:
“无法启动 Activity ComponentInfo{com.herman.homeSchedule/com.herman.homeSchedule.MainActivity}:java.lang.IllegalStateException:findViewById(R.id.fab_new_schedule) 不得为 null”
知道如何修复它吗???
这是我的 float 操作按钮 xml
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab_new_schedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:clickable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:srcCompat="@drawable/ic_add"
android:focusable="true" />
这是我在 onCreate 中的代码
val fab : View = findViewById(R.id.fab_new_schedule)
fab.setOnClickListener {
Log.i("Button", "FAB clicked")
val now = Calendar.getInstance()
val datePicker = DatePickerDialog(
this, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
Toast.makeText(
this, "year : " + year
+ "\n Month : " + month
+ "\n Date: " + dayOfMonth, Toast.LENGTH_SHORT
).show()
},
now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH)
)
datePicker.show()
}
提前谢谢
最佳答案
在您的 Activity 布局中找不到FloatingActionButton
。
您需要将 FloatingActionButton
添加到 activity_main
布局(或您的调用方式),然后调用 setContentView(R.layout.activity_main)
code> 在 MainActivity 的 onCreate 中。
如果您这样做了,但仍然不起作用,您能否提供包含 FAB 的完整布局?
关于java - 使用 fab 调用日期选择器对话框时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61407215/