我正在开发一个Android项目,我创建了一个包含星期几的下拉列表(Spinner),现在我想要在所选星期的缩写(mon, tue, wed等)中显示,但是在下拉列表中需要显示完整的星期名称(Monday,Tuesday,Wednesday等)。
我应该怎么做?我已经使用默认的XML布局创建了最简单的Spinner。
我正在开发一个Android项目,我创建了一个包含星期几的下拉列表(Spinner),现在我想要在所选星期的缩写(mon, tue, wed等)中显示,但是在下拉列表中需要显示完整的星期名称(Monday,Tuesday,Wednesday等)。
我应该怎么做?我已经使用默认的XML布局创建了最简单的Spinner。
<androidx.appcompat.widget.AppCompatSpinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
string-array
。<string-array name="Weekdays">
<item>Monday</item>
<item>Tuesday</item>
<item>Wednesday</item>
<item>Thursday </item>
<item>Friday</item>
<item>Saturday</item>
<item>Sunday</item>
</string-array>
<string-array name="WeekdaysAbbreviations">
<item>Mon</item>
<item>Tue</item>
<item>Wed</item>
<item>Thu</item>
<item>Fri</item>
<item>Sat</item>
<item>Sun</item>
</string-array>
那么你可以得到以下工作日
val weekdays = resources.getStringArray(R.array.Weekdays)
接下来的测试内容如下:
val weekDays = resources.getStringArray(R.array.Weekdays)
val abbreviationWeekDays = resources.getStringArray(R.array.WeekdaysAbbreviations)
//find the spinner
val spinner = findViewById<AppCompatSpinner>(R.id.spinner)
//create an adapter with the weekdays
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, weekDays)
//set the adapter
spinner.adapter = adapter
spinner.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View, position: Int, id: Long
) {
//find the first TextView of the Adapter
val selectedText = parent.getChildAt(FIRST_POSITION) as TextView
//As the abbreviationWeekDays and WeekDays have the same size, you can get the position selected on weebDays and then print what you have on abbreviationdays
//Another option would be selectedText.text = weekDays[position].substring(0,4)
selectedText.text = abbreviationWeekDays[position]
}
override fun onNothingSelected(parent: AdapterView<*>) {
//Nothing selected \o/
}
}
输出:
此外,我在我的Github账户上创建了一个示例代码库
substring()
。String str = "Monday";
String firstThree = str.substring(0,4);
System.out.println(firstThree);
输出
Mon
spinner.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item,new String[]{"Monday","Tuesday","Wednesday"});
从你的问题中我猜测你想要做的就是设置一个 OnItemSelectedListener,处理你的下拉列表中的元素,并在任何你想要显示的视图中显示缩写形式。