Kotlin - 尝试使用 findViewById() 从 Fragment 填充微调器,但上下文:这会引发错误

Kotlin - Trying to populate spinner from Fragment using findViewById(), but context: this is throwing an error

强制性前言:我对 Kotlin 和 Android Studio 还很陌生。如标题所述,我正在尝试从片段中填充 Android Studio 中的微调器。首先,我遇到了 findViewById(R.id.spinner) 的问题,但我相信我已经通过在它前面加上 root..

来解决它

目前,唯一抛出的错误是 context: this 行。最终,我想使用这个微调器允许用户按不同的纽约行政区进行过滤(因此,boroughs_array。这是我在 FilterFragment 中的当前代码——我尝试填充微调器的尝试从下面开始 return root.

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 不是正确的上下文,因为我在片段中。 off-chance 这是正确的,我不太确定如何处理这个问题。 如果你能对这个问题有所启发,我将永远感激不已。

您需要使用 context!! 而不是 thisthis指的是当前的Fragment,不是Context。当前 Fragment 引用了 Context,通过 this.getContext() 或简称 context 访问。

你需要context!!的原因是因为getContext()nullable(它可能return null)。在这种情况下 'force unwrap' (!!) 是安全的,因为 context 永远不会是 null inside onCreateView().

我发现的另一个问题是,您在设置微调器之前 return 从 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
}

此外,只是为了进一步说明 - 您可能已经看到一些示例,其中 this 被传递给 context。这通常在 Activity 内部完成,因为 Activity 确实扩展了 Context.

您可以这样访问 context

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
    }
}