Android fragments Kotlin-尝试使用findViewById()从片段填充微调器,但上下文:这会引发错误
强制性前言:我对科特林和安卓工作室很陌生。正如标题所述,我试图从一个片段中填充Android Studio中的微调器。首先,我在Android fragments Kotlin-尝试使用findViewById()从片段填充微调器,但上下文:这会引发错误,android-fragments,kotlin,android-spinner,Android Fragments,Kotlin,Android Spinner,强制性前言:我对科特林和安卓工作室很陌生。正如标题所述,我试图从一个片段中填充Android Studio中的微调器。首先,我在findViewById(R.id.spinner)中遇到了一个问题,但我相信我已经通过在它前面加根来解决了这个问题。 当前,引发的唯一错误是上下文:这一行。最后,我希望使用此微调器允许用户按不同的纽约行政区进行过滤(因此,boroughs\u array) override fun onCreateView( inflater: LayoutInfla
findViewById(R.id.spinner)
中遇到了一个问题,但我相信我已经通过在它前面加根来解决了这个问题。
当前,引发的唯一错误是上下文:这一行。最后,我希望使用此微调器允许用户按不同的纽约行政区进行过滤(因此,boroughs\u array
)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
filtersViewModel =
ViewModelProviders.of(this).get(FiltersViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_filters, container, false)
return root
val spinner: Spinner = root.findViewById(R.id.spinner)
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter.createFromResource(
this,
R.array.boroughs_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spinner.adapter = adapter
}
我目前的假设是,这个不是正确的上下文,因为我在一个片段中。如果这是正确的,我真的不知道如何处理这个问题。如果你能对这个问题有所了解,我将永远感激。你需要使用上下文!!
而不是这个
此
引用当前的片段
,它不是上下文
。但是当前的片段
引用了上下文
,可通过this.getContext()
或简称上下文
访问
您需要context!!
的原因是getContext()
可以null
(它可能返回null
)。在这种情况下,“强制展开”(!!
)是安全的,因为context
在onCreateView()中永远不会null
我发现的另一个问题是,在设置微调器之前,您正在从onCreateView()
函数返回
请尝试以下方法:
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
filtersViewModel = ViewModelProviders.of(this).get(FiltersViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_filters, container, false)
val spinner: Spinner = root.findViewById(R.id.spinner)
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter.createFromResource(
context!!,
R.array.boroughs_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spinner.adapter = adapter
return root
}
另外,为了进一步澄清,您可能已经看到了一些示例,其中此
被传递给上下文
。这通常是在活动
内部完成的,因为活动
确实扩展了上下文您可以像这样访问上下文
:
context?.let { context ->
ArrayAdapter.createFromResource(
context,
R.array.boroughs_array,
android.R.layout.simple_spinner_item
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
}
}