android-fragments 自动完成片段中的文本视图

30byixjq  于 2022-11-14  发布在  Android
关注(0)|答案(2)|浏览(181)

我想在fragment中创建一个autoCompleteTextView,但是数组适配器带来了一个错误,指出“以下函数都不能用提供的参数调用”。那么,我应该如何在fragment类中使用数组适配器呢?

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val frequencyArray = ArrayList<String>()
    frequencyArray.add("Daily")
    frequencyArray.add("Weekly")
    frequencyArray.add("Monthly")

    val adapter = ArrayAdapter(
        this,
        com.google.android.material.R.layout.support_simple_spinner_dropdown_item,
        frequencyArray
    )

    var autoComplete = view?.findViewById<AutoCompleteTextView>(R.id.notAuto)
    autoComplete?.setAdapter(adapter)
}
ig9co6j1

ig9co6j11#

您尝试使用的构造函数如下:

public ArrayAdapter (Context context, 
                int resource, 
                List<T> objects)

第一个参数是Context,你传递的是this,也就是Fragment。但是Fragment * 不是 * Context(不像Activity),所以你必须获取一个。只要用requireContext()代替,在调用onViewCreated的时候你就会有一个了(你在onCreate之前得到它)

val adapter = ArrayAdapter(
        requireContext(),
        com.google.android.material.R.layout.support_simple_spinner_dropdown_item,
        frequencyArray
    )
a7qyws3x

a7qyws3x2#

试试这个?

class SecondFragment : Fragment() {

    lateinit var autoTextView : AutoCompleteTextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val inflate = inflater.inflate(R.layout.fragment_second, container, false)

        autoTextView = inflate.findViewById(R.id.autoTextView)

        val languages
                = resources.getStringArray(R.array.Languages)

        // Create adapter and add in AutoCompleteTextView
        val adapter1
                = ArrayAdapter<String>(requireContext(),
            android.R.layout.simple_list_item_1, languages)
        autoTextView.setAdapter(adapter1)

        return inflate
    }
}

并检查https://prnt.sc/cQpmLyDO4WsV

相关问题