How to get the left margin of a centered view in android?

I have view that is centered in xml by android:layout_centerHorizontal=”true”. How do I get the leftMargin of it, so I can align other views with it?

I tried using getLayoutParams on the centered view but it didn’t work. It seems to report a leftMargin of 0.

I also tried to compute the leftMargin with (screenWidth-view width)/2, but it gives a slightly higher value than expected. More specifically, this is my code:

    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int screenWidth = size.x;
    int screenHeight  = size.y;

    TextView button1 = (TextView) findViewById(R.id.button1);
    RelativeLayout.LayoutParams params=(RelativeLayout.LayoutParams)
    button1.getLayoutParams();
    params.height=102;
    params.width=114;
    params.topMargin =0;
    button1.setLayoutParams(params);
    params=(RelativeLayout.LayoutParams) button1.getLayoutParams();
    int leftMargin = params.leftMargin;

    TextView button2 = (TextView) findViewById(R.id.button2);
    params=(RelativeLayout.LayoutParams) button2.getLayoutParams();
    params.height=102;
    params.width=114;
    params.leftMargin =leftMargin;
    params.topMargin =102;
    button2.setLayoutParams(params);

    TextView button3 = (TextView) findViewById(R.id.button3);
    params=(RelativeLayout.LayoutParams) button3.getLayoutParams();
    params.height=102;
    params.width=114;
    params.leftMargin =(screenWidth-114)/2;
    params.topMargin =204;
    button3.setLayoutParams(params);

Button1 is centered in xml.
Button2 is left-aligned, not centered.
Button3 is more or less centered, but slightly to the right.

So,

1) how do I get the left margin of a view centered in xml?

2) how do I center (exactly) a view in code? Does getDefaultDisplay reports an higher width than the real screen width?


Source: xml

Leave a Reply