Kotlin-正在尝试使用findViewById()从片段填充微调控制项,但上下文:这引发错误 [英] Kotlin - Trying to populate spinner from Fragment using findViewById(), but context: this is throwing an error

查看:17
本文介绍了Kotlin-正在尝试使用findViewById()从片段填充微调控制项,但上下文:这引发错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

强制性前言:我对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不是正确的上下文,因为我在片段中。如果这是正确的,我真的不确定该如何处理。如果您能在这个问题上提供任何帮助,我将永远感激。

推荐答案

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

您需要context!!的原因是getContext()nullable(它可能返回null)。在这种情况下,"强制展开"(!!)是安全的,因为context永远不会在onCreateView()内。

我发现的另一个问题是,您在设置微调器之前从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传入this的例子。这通常在Activity内完成,因为Activity确实扩展了Context

这篇关于Kotlin-正在尝试使用findViewById()从片段填充微调控制项,但上下文:这引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆