Spinner的基本用法Demo

代码

kotlin

//点击协议选择
val protocols = resources.getStringArray(R.array.protocol)
val adapter = ArrayAdapter(this, R.layout.item_protocol, protocols)
viewBinding.serverProtocolSelect.adapter = adapter
viewBinding.serverProtocolSelect.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {}

override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, pos: Int, id: Long) {
when (protocols[pos]) {
"https" -> ServiceConfig.is_service_https = true
else -> ServiceConfig.is_service_https = false
}
}
}

​另一种写法(从sharedPreferences)中择取:​

//模式选择
val modes = resources.getStringArray(R.array.mode)
val modeNum = modes.indexOf(ServiceConfig.mode_change)
val adapter = ArrayAdapter(this, R.layout.item_mode, modes)
viewBinding.chooseModeSpinner.adapter = adapter
viewBinding.chooseModeSpinner.setSelection(modeNum)//设置系统原模式
viewBinding.chooseModeSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {}

override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, pos: Int, id: Long) {
selectedItem = modes[pos]
}
}

Layout
​​​layout​

<Spinner
android:id="@+id/server_protocol_select"
style="@style/Spinner.LittleList"
android:entries="@array/protocol" />

<style name="Spinner.LittleList">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">@dimen/spinner.list</item>
<item name="android:overlapAnchor">false</item>
<item name="android:spinnerMode">dropdown</item>
<item name="android:theme">@style/SpinnerColor</item>
</style>

​item​

<?xml version="1.0" encoding="utf-8"?>
<TextView style="@style/Spinner.ListItem" />

<style name="Spinner.ListItem">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">@dimen/spinner.list</item>
<item name="android:background">@drawable/settings_selector_protocol</item>
<item name="android:gravity">center</item>
<item name="android:textColor">@color/white</item>
<item name="android:textSize">@dimen/tip</item>
<item name="android:textStyle">bold</item>
<item name="android:padding">@dimen/spinner.padding</item>
<item name="android:text">123</item>
</style>

​array​

<resources>
<string-array name="protocol">
<item>http</item>
<item>https</item>
</string-array>
</resources>

示例:

【Android】Spinner的基本用法Demo_安卓
【Android】Spinner的基本用法Demo_安卓_02

一些其他的要点

​更改spinner 箭头颜色​

//在styles 里面添加一个新的style 可以叫 SpinnerStyle
<style name="SpinnerStyle">
<item name="colorControlNormal">#ddffffff</item> <!--改变了spinner的颜色 -->
</style>

然后在layout中让相应的spinner 引用这个theme

<Spinner
android:id="@+id/sp_homefragment_plane_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/SpinnerStyle"
android:entries="@array/breeze"
android:dropDownWidth="match_parent"
</Spinner>

​从标签底部向下弹出​

android:overlapAnchor="false"