java 中距离左边距代码_如何在android中获得居中视图的左边距?

我的视图以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报告的宽度是否高于实际屏幕宽度?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值