首页 > 解决方案 > 如何将分隔线添加到我的下拉列表(微调器)?

问题描述

点击前

点击后 - 我想添加这样的蓝线

我想在我的下拉列表中添加分隔符。

我使用了在 stackoverflow 上找到的解决方案,但它们不起作用。

这是我在 xml 片段中的 xml 代码

<Spinner
     android:id="@+id/spinner1"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:spinnerMode="dialog"
     android:background="@drawable/spinner">

</Spinner>

这是 spinner.xml。它是定义边界,形状和图像(“点击按钮”)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <layer-list>

            <item>
                <shape android:shape="rectangle">
                    <padding
                        android:left="0dp"
                        android:top="0dp"
                        android:right="0dp"
                        android:bottom="1.5dp"
                        />

                    <gradient android:startColor="@color/white" android:endColor="@color/white" android:angle="270" />
                    <stroke android:width="2px" android:color="@color/colorPrimary2" />
                    <corners android:radius="0dp" />
                </shape>
            </item>

                <item android:gravity="center|right" android:drawable="@drawable/ic_spinner_drop_down"/>



        </layer-list>
    </item>
</selector>

标签: javaandroidxmlspinnerandroid-spinner

解决方案


这仅适用于 spinnerMode="dropdown"... 对于对话框模式,必须在运行时通过适配器添加分隔符(引用的示例也使用下拉菜单,但在实现它并将模式更改为对话框之后,分隔符仍在显示)。

只需尝试将其添加到资源目录中的styles.xml文件中:values

    <style name="SpinnerStyle" parent="Widget.AppCompat.ListView.DropDown">
        <item name="android:divider">#0000ff</item>
        <item name="android:dividerHeight">0.5dp</item>
    </style>

    <style name="SpinnerTheme" parent="AppTheme">
        <item name="android:dropDownListViewStyle">@style/SpinnerStyle</item>
    </style>

然后,您可以style向该文件中已有的标签添加一个额外的子节点(这会将样式应用于所有微调器):

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- ... -->
        <!-- ... -->
        <!-- ... -->
        <!-- ... some existing lines -->

        <!-- ... new line to add:-->
        <item name="android:dropDownListViewStyle">@style/SpinnerStyle</item>
    </style>

或者...您可以将该样式添加到片段 XML 中的特定 Spinner 标记中(这会将样式仅应用于此微调器):

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"
        android:background="@drawable/spinner"
        android:theme="@style/SpinnerTheme">
    </Spinner>

推荐阅读