android动态获取设置控件高度

动态获取控件高度

一、

	View view = findViewById(R.id.xxx);

  //声明一个boolean,因为addOnGlobalLayoutListener会重复执行,控制它启动后只执行一次
  private boolean isCompletedDraw = false;   
  
    //获取TextVie控件的高度,然后设置给ImageView
        view .getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (!isCompletedDraw){
                    isCompletedDraw = true;
                    // h就是TextView的高度,h就是TextView的宽度
                    int mHeight  = view .getMeasuredHeight();
                    int mWidth  = view .getMeasureWidth();
                }
            }
        });

二、

		View view = findViewById(R.id.xxx);
        view.post(new Runnable() {
            @Override
            public void run() {
                int mHeight = view.getHeight();
                int mWidth = view.getWidth();
            }
        });

动态设置控件宽高和margin

		View view = findViewById(R.id.xxx);
		ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                layoutParams.leftMargin =10;
                layoutParams.height = 100;
                layoutParams.width = 100;
                view.setLayoutParams(layoutParams);

你可能感兴趣的:(安卓)