android – “如何将参数传递给drawable”或“使用渐变和可变图像创建按钮”

我的 android项目中有一个自定义drawable,它应该是一个按钮的背景.但每个按钮也应该支持图标和文本.

到目前为止我尝试的是以下内容

我有一个名为“btn_background.xml”的drawable

<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)属性.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...