View在onCreate的时候,没有渲染组件,所以获取到的宽度和高度为0,
需要添加一个观察者,在layout渲染后再去取宽高。代码如下:
private Button btn_icon; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_button); btn_icon = findViewById(R.id.btn_icon); ViewTreeObserver vto = btn_icon.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { btn_icon.getViewTreeObserver().removeGlobalOnLayoutListener(this); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) btn_icon.getLayoutParams(); Context ctx = btn_icon.getContext(); int marginLen = (DisplayUtil.getScreenWidth(ctx) - btn_icon.getWidth()) / 2; lp.setMargins(marginLen, 20, marginLen, 20); btn_icon.setLayoutParams(lp); } }); }
参考:https://blog.csdn.net/zheng5229875/article/details/39314159