开发者

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

开发者 https://www.devze.com 2023-04-05 01:24 出处:网络
I have a custom drawable in my android project that should be the background of a button. But each button should also support an icon AND a text.

I have a custom drawable in my android project that should be the background of a button. But each button should also support an icon AND a text.

What I tried so far is the following:

I have a drawable called "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>

And in my layout file i use that like this:

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

This is getting me somewhere close... but there are two problems: * The image is stretched across the whole button * I can't just change the image in the layout file... so i would have to make a seperate btn_whatever.xml file for each icon?!?

The other solution that I tried was to use an ImageButton instead of an Button and set the background to my btn_b开发者_如何学Goackground.xml .... this would make me able to select the image in the layout file... but then i can't give it a text....

I would be happy to hear about your solutions for my problem :)

Thanks a lot!


Try to use android:drawableLeft (or similar Top, Right, Bottom) attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号