我是android和kotlin的新手,所以请原谅要解决的一个非常简单的问题!
我已经使用导航体系结构组件创建了一个基本应用程序,使用了底部的导航栏和三个导航选项。每个导航选项都指向一个专用片段,该片段仅显示一个文本框。到目前为止,一切正常。
在其中一个片段(fragement_record.xml / RecordFragmet.kt)上,我试图加载单个微调器,该微调器要从我的strings.xml文件中定义的字符串数组中填充。当我构建并运行该应用程序时,它可以正常工作,但可见的微调框不包含任何数据-它为空。
我已经研究了Stack Overflow和许多其他站点,但不清楚我在做什么错。
我的字符串数组如下所示:
<string-array name="shot_type_values">
<item>Select shot type…</item>
<item>Tee</item>
<item>Approach</item>
<item>Short</item>
<item>Putt</item>
</string-array>
我的布局文件fragment_record.xml如下所示:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".RecordFragment">
<Spinner
android:id="@+id/shot_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginBottom="10dp"
android:background="@color/colorText"
android:minHeight="70dp"
android:visibility="visible" />
</FrameLayout>
我的 Activity 文件RecordFragment.kt如下所示:
package digitalaidconsulting.com.proshotpoc
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.SpinnerAdapter
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import kotlinx.android.synthetic.*
import kotlinx.android.synthetic.main.fragment_record.*
class RecordFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val shotType = view?.findViewById<Spinner>(R.id.shot_type)
this.context?.let {
ArrayAdapter.createFromResource(
it,
R.array.shot_type_values,
android.R.layout.simple_list_item_1
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
if (shotType != null) {
shotType.adapter = adapter
}
}
}
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_record, container, false)
}
}
这是构建成功运行(模拟器)后的最终结果:
感谢所有的帮助!
最佳答案
您的观点目前尚未膨胀。
您可以将代码移动到onViewCreated方法或使用通过以下方式创建的 View :
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_record, container, false)
val shotType = view?.findViewById<Spinner>(R.id.shot_type)
this.context?.let {
ArrayAdapter.createFromResource(
it,
R.array.shot_type_values,
android.R.layout.simple_list_item_1
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
if (shotType != null) {
shotType.adapter = adapter
}
}
}
return view
}
关于android - Android Spinner未填充| Android Kotlin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62233790/