如何使用图像箭头自定义微调器

时间:2018-10-26 23:19:35

标签: android

我有一个微调器,需要更改箭头并使其在边框内

像这样 enter image description here

我在stackoverflow上尝试了多种方法 设置背景可绘制,设置android:button ..etc但没有运气。我得到了但被拉伸了,或者我得到了选择列表中的箭头,或者我得到了覆盖整个屏幕的选择 如何使用自己的drawable获取微调器?

1 个答案:

答案 0 :(得分:0)

有两种方法可以实现微调器的自定义背景。

  • 使用9个补丁图像(简便方法)
  • 使用LayerList(复杂的方法)

因为我的扩展名没有.png,所以我将演示第二个。

背景包含2层,前者是一个圆角矩形,后者是箭头位图。

这是箭头位图(ic_arrow_24dp),您可以用自己的箭头位图替换。

enter image description here

background_spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <!-- First layer is a rounded rectangle -->
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="#808080"/>
            <corners android:radius="3dp"/>
        </shape>
    </item>

    <!-- Second layer is a arrow bitmap -->
    <item android:gravity="right|center_vertical">
        <bitmap android:src="@drawable/ic_arrow_24dp"/>
    </item>

</layer-list>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:padding="20dp"
    android:orientation="vertical">

    <Spinner 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content"
        android:background="@drawable/background_spinner"
        android:paddingRight="24dp"/> <!-- Prevent content of the spinner from overlapping over the arrow icon, the size is equal to size of the arrow icon -->

</LinearLayout>