gpt4 book ai didi

android - Kotlin DatePicker弹出窗口在 fragment 内不起作用:WindowManager $ BadTokenException:无法添加窗口- token null无效;

转载 作者:行者123 更新时间:2023-12-02 13:31:23 24 4
gpt4 key购买 nike

android.view.WindowManager $ BadTokenException:无法添加窗口- token null无效;您的 Activity 正在进行吗?

我试图从this弹出DatePicker,并且在将其放入片段之前,它工作正常。DatePickerDialog(...).show()发生错误
而且我认为由于片段的上下文,它无法正常工作。

这是代码(在片段中)

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view: View = inflater!!.inflate(R.layout.fragment_fill1, container, false)

textview_date = view.text_view_date
button_date = view.button_date
textview_date!!.text = "--/--/----"

// create an OnDateSetListener
val dateSetListener = object : DatePickerDialog.OnDateSetListener {
override fun onDateSet(
view: DatePicker, year: Int, monthOfYear: Int,
dayOfMonth: Int
) {
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
updateDateInView()
}
}

button_date!!.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
DatePickerDialog(
getActivity()!!.getApplicationContext(), //Context to fill
dateSetListener,
// set DatePickerDialog to point to today's date when it loads up
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
).show() //Error on this line
}

})

// Return the fragment view/layout
return view
}

//Date Picker
private fun updateDateInView() {
val myFormat = "dd/MM/yyyy" // mention the format you need
val sdf = SimpleDateFormat(myFormat, Locale.US)
textview_date!!.text = sdf.format(cal.getTime())
}

谢谢!!

最佳答案

对话框需要 Activity 上下文。

更换

getActivity()!!.getApplicationContext()


requireActivity()

关于android - Kotlin DatePicker弹出窗口在 fragment 内不起作用:WindowManager $ BadTokenException:无法添加窗口- token null无效;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61237173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com