我对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>
我的活动文件,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)
}
}
这是构建成功运行(仿真器)后的最终结果:
screenshot of empty spinner after app load
非常感谢所有帮助!
将您的代码移至onViewCreated方法