如何解决如何在 Android Spinner 中仅显示 3 个字符?
我正在开发一个 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/
}
}
输出:
我还创建了一个 Sample repository on my Github account
,使用substring()
String str = "Monday";
String firstThree = str.substring(0,4);
System.out.println(firstThree);
输出
Mon
,
您的 Spinner 可能如下所示
spinner.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item,new String[]{"Monday","Tuesday","Wednesday"});
根据您的问题,我猜您想要做的只是设置一个 OnItemSelectedListener,为微调器中的元素处理该问题,并在您希望的任何视图中显示缩写形式
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。