简体   繁体   中英

Margin of buttons in linear layout

I am creating some buttons and add them to a linear layout which is defined as

<LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/mylayout">

    </LinearLayout>

The buttons are created with

for (int i = 0; i < 3; i++)

    {
        Button btn = new Button(activity);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(1, 1, 1, 1);

        btn.setText("Button");
        btn.setPadding(0, 0, 0, 0);

        mylayout.addView(pv, lp);

    }

These buttons always have a margin (about 3px) which I'd like to remove. Is there anything I am missing? If I use a custom view which I created there is no space between them.

Should I set

lp.setMargins(-3, -3, -3, -3);

which removes the margin? Is there a drawback with this?

I do not really think they have a margin but it is related to the background of the button. Probably the default background of the button has a image like this one:

http://developer.android.com/guide/developing/tools/draw9patch.html

which includes fiction margins. Here you can find more info about 9-Patch.

http://developer.android.com/guide/topics/resources/drawable-resource.html

In my opinion if you want to remove the "margins", you should create a different background for the image because the -3 value is not a good workaround (IHMO).

Why are you using Layout Params .. simply add the view after its creation... This will surely remove the problem

for (int i = 0; i < 3; i++)

{
    Button btn = new Button(activity);


    btn.setText("Button");


    mylayout.addView(pv);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM