"How to pass a parameter into a drawable"或"Create button with gradient and changeable image"



我有一个自定义绘制在我的android项目,应该是一个按钮的背景。但是每个按钮还应该支持一个图标和一个文本。

到目前为止我尝试的是:

我有一个可绘制的名为"btn_background.xml"

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
   <layer-list >
       <item>
           <shape xmlns:android="http://schemas.android.com/apk/res/android"
                android:shape="rectangle">
                <gradient android:startColor="#ff0000" 
                    android:endColor="#ee1111" 
                    android:type="linear"
                    android:angle="90"/>
                <stroke android:color="#ff0000" 
                   android:width="1dip"/>
                <size android:width="80dip"
                      android:height="40dip" />
           </shape>
       </item>
       <item android:drawable="@drawable/btn_search"/>
   </layer-list>
</item>

在我的布局文件中,我像这样使用:

<Button android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:text="Button" 
        android:background="@drawable/btn_background"
        android:textColor="#ffffff"/>

这让我接近…但有两个问题:*图像在整个按钮上拉伸*我不能改变布局文件中的图像…所以我必须为每个图标创建一个单独的btn_whatever.xml文件?

我尝试的另一个解决方案是使用ImageButton而不是Button,并将背景设置为btn_background.xml ....这将使我能够在布局文件中选择图像…但是我不能给它一个文本....

我很高兴听到你对我的问题的解决方案:)

非常感谢!

尝试使用android:drawableLeft(或类似的Top, Right, Bottom)属性

最新更新