“ Light Theme”样式是我想要更改为看起来像其余小部件的样式
这是我的微调代码
<Spinner
android:id="@+id/ui_mode"
style="@style/GenericText.SettingsSubtext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/amount"
android:entries="@array/ui_mode"
tools:listitem="@layout/spinner_popup_item" />
无法直接从XML更改Spinner样式。但是,您可以实现一个类来实现。在我的实现中,当您单击微调器时,我需要一些时间来增加一些效果。
微调器类
class MySpinner : AppCompatAutoCompleteTextView, AdapterView.OnItemClickListener {
companion object {
private const val MAX_CLICK_DURATION = 200
}
private var startClickTime: Long = 0
private var isPopup: Boolean = false
private var mPosition = ListView.INVALID_POSITION
constructor(context: Context?, attributeSet: AttributeSet?, defStyleAttr: Int) : super(
context,
attributeSet,
defStyleAttr
)
constructor(context: Context?, attributeSet: AttributeSet?) : super(context, attributeSet)
constructor(context: Context?) : super(context)
init {
onItemClickListener = this
}
override fun enoughToFilter(): Boolean = true
override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
super.onFocusChanged(focused, direction, previouslyFocusedRect)
if (focused) {
performFiltering("", 0)
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
keyListener = null
dismissDropDown()
} else {
isPopup = false
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
if (!isEnabled)
return false
when (event.action) {
MotionEvent.ACTION_DOWN -> {
startClickTime = Calendar.getInstance().timeInMillis
super.performClick()
}
MotionEvent.ACTION_UP -> {
val clickDuration = Calendar.getInstance().timeInMillis - startClickTime
if (clickDuration < MAX_CLICK_DURATION) {
isPopup = if (isPopup) {
dismissDropDown()
false
} else {
requestFocus()
showDropDown()
true
}
}
}
}
return super.onTouchEvent(event)
}
override fun onItemClick(adapterView: AdapterView<*>, view: View, position: Int, id: Long) {
mPosition = position
isPopup = false
}
override fun setCompoundDrawablesWithIntrinsicBounds(
left: Drawable?,
top: Drawable?,
right: Drawable?,
bottom: Drawable?
) {
var rightInline = right
val dropdownIcon = ContextCompat.getDrawable(context, R.drawable.ic_baseline_arrow_drop_down_24dp)
if (dropdownIcon != null) {
val value = TypedValue()
context!!.theme.resolveAttribute(R.attr.colorAccent, value, true)
rightInline = dropdownIcon
rightInline.setColorFilter(value.data, PorterDuff.Mode.SRC_ATOP)
}
super.setCompoundDrawablesWithIntrinsicBounds(left, top, rightInline, bottom)
}
fun getPosition(): Int = mPosition
fun setPositionAndText(position: Int, text: String) {
mPosition = position
setText(text)
}
}
和您的XML
<com.yourpackages.MySpinner
android:id="@+id/ui_mode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/amount"
android:entries="@array/ui_mode"/>