gpt4 book ai didi

android - 如何在 Android Spinner 中仅显示 3 个字符?

转载 作者:行者123 更新时间:2023-12-04 00:52:26 25 4
gpt4 key购买 nike

我正在开发一个 android 项目,我在工作日制作了一个 Spinner,现在我只想显示在 Spinner 中选择的任何一天的缩写(星期一、星期二、星期三等),但全名下拉列表中的天数(星期一、星期二、星期三等)。我应该怎么做?我已经用默认的 xml 布局制作了最简单的 Spinner。

最佳答案

注意:这可能无法编译它只是一个“伪”给你一个方法的想法。

您创建一个普通的 Spinner(您也可以创建一个 CustomView,然后将逻辑放在那里,但我会选择最快的那个)

<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/
}
}

输出:

enter image description here enter image description here

我还创建了一个 Sample repository on my Github account

关于android - 如何在 Android Spinner 中仅显示 3 个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65489668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com