Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting margins for buttons using drawable in android

I'm developing an android application in eclipse. I have a set of buttons and I want to insert some space between them. I'm setting the background of these buttons using an xml file(background.xml) in the drawables. For inserting spaces I'm using the following lines of code for all the buttons seperatley in the main xml file.

    android:layout_marginLeft = "10dip"
    android:layout_marginRight = "10dip"
    android:layout_marginTop = "10dip"
    android:layout_marginBottom = "10dip"

My question is, Is there a way to set the margins by modifying the background.xml file. Otherwise I have to edit all the buttons whenever I modify the margins. Thanks in advance.

like image 536
jjpp Avatar asked Jan 14 '23 08:01

jjpp


1 Answers

This is a perfect example of where to use a style. A style is simply a group of common attributes that you wish to apply to a large number of objects. For instance, you could create a style called buttonStyle using the following code, which would do exactly what you want. If you decide you want to change the margin, you simply change the style. If you decide you want to do different margin values for different sized phones, just create two styles, one for normal, one for large, and more if required.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="buttonStyle">
        <item name="android:layout_marginLeft">10dip</item>
        <item name="android:layout_marginRight">10dip</item>
        <item name="android:layout_marginTop">10dip</item>
        <item name="android:layout_marginBottom">10dip</item>
    </style>
</resources>

Then the button code can be simplified to just this:

style="@style/buttonStyle"

When you change the style, all buttons will change automatically. You can do nested styles as well. See the API for more info.

like image 178
PearsonArtPhoto Avatar answered Jan 17 '23 15:01

PearsonArtPhoto