我的视图以xml为中心由android:layout_centerHorizontal =“true” . 我如何获得它的leftMargin,所以我可以将其他视图与它对齐?
我尝试在居中的视图上使用getLayoutParams,但它不起作用 . 它似乎报告了一个0的leftMargin .
我还尝试使用(screenWidth-view width)/ 2来计算leftMargin,但它给出的值略高于预期值 . 更具体地说,这是我的代码:
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以xml为中心 . Button2左对齐,不居中 . Button3或多或少居中,但略微向右 .
所以,
1)如何获得以xml为中心的视图的左边距?
2)如何在代码中居中(确切地)一个视图? getDefaultDisplay报告的宽度是否高于实际屏幕宽度?
1 回答
您可以直接询问布局以使视图对齐 . 例如,
编辑:要获得居中视图的相对偏移量,这可能就足够了:
看到:
View.getTop()和View.getLeft()