How to get the button's border size in Android

爷,独闯天下 提交于 2019-12-07 08:29:30

My initial code recommendation from the comments can be found here. The implementation done by Dan Bray is:

final Button button = new Button(this);
params = new RelativeLayout.LayoutParams(50, 50);
layout.addView(button, params);
button.post(new Runnable()
{
@Override
public void run()
{
    button.buildDrawingCache();
    Bitmap viewCopy = button.getDrawingCache();

    boolean stillBorder = true;
    PaddingLeft = 0;
    PaddingTop = 0;
    while (stillBorder)
    {
        int color = viewCopy.getPixel(PaddingLeft, button.getHeight() / 2);
        if (color != Color.TRANSPARENT)
            stillBorder = false;
        else
            PaddingLeft++;
    }              
    stillBorder = true;
    while (stillBorder)
    {
        int color = viewCopy.getPixel(button.getWidth() / 2, PaddingTop);
        if (color != Color.TRANSPARENT)
            stillBorder = false;
        else
            PaddingTop++;
    }
}
});

Not really clear on the question - you want the margins of the underlying view and then the set the size of the button to match ? Then Have you tried

ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();

margins are accessible via

lp.leftMargin;
lp.rightMargin;
lp.topMargin;
lp.bottomMargin;

Details here:http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html

This gets the width and height of the button's border:

final Button button = new Button(this);
params = new RelativeLayout.LayoutParams(50, 50);
layout.addView(button, params);
button.post(new Runnable()
{
    @Override
    public void run()
    {
        button.buildDrawingCache();
        Bitmap viewCopy = button.getDrawingCache();

        boolean stillBorder = true;
        PaddingLeft = 0;
        PaddingTop = 0;
        while (stillBorder)
        {
            int color = viewCopy.getPixel(PaddingLeft, button.getHeight() / 2);
            if (color != Color.TRANSPARENT)
                stillBorder = false;
            else
                PaddingLeft++;
        }              
        stillBorder = true;
        while (stillBorder)
        {
            int color = viewCopy.getPixel(button.getWidth() / 2, PaddingTop);
            if (color != Color.TRANSPARENT)
                stillBorder = false;
            else
                PaddingTop++;
        }
    }
});

Assuming you are using a nine patch background image, there is a much easier way.

In the nine patch image, you can define a padding box. This padding box will automatically be applied to the contents you set. No need to recalculate the paddings manually in that case.

Note that you should not set a padding on views using a nine patch as a background as the padding from the nine patch will be ignored.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!