Android中获取控件宽高的4种方法集合

https://www.jb51.net/article/134422.htm

1.onWindowFocusChanged

这个方法会被调用多次,在View初始化完毕后会调用,当Activity的窗口得到焦点和失去焦点都会被调用一次(Activity继续执行和暂停执行时)。

?

1

2

3

4

5

6

7

8

@Override

public void onWindowFocusChanged(boolean hasFocus) {

  super.onWindowFocusChanged(hasFocus);

  if (hasFocus) {

    int width = view.getMeasuredWidth();

    int height = view.getMeasuredHeight();

  }

}

2.view.post

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

@Override

protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  ViewGroup root = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.activity_main, null, false);

  setContentView(root);

  final View view = root;

  view.post(new Runnable() {

    @Override

    public void run() {

      int width = view.getMeasuredWidth();

      int height = view.getMeasuredHeight();

      Log.i(TAG, width + " " + height);

    }

  });

}

具体原理暂时还不懂,不过应该是view封装的异步回调初始化后,view的测绘多半也完成了,这是一个同步的过程。所以才可以接收到消息。

3.ViewTreeObserver

他有许多回调。比如当View树的状态发生改变或者View树内部的View可见性发现改变时,onGlobalLayout方法将被回调。

?

1

2

3

4

5

6

7

8

9

10

11

final View view = root;

ViewTreeObserver observer = view.getViewTreeObserver();

observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

  @Override

  public void onGlobalLayout() {

    view.getViewTreeObserver().removeGlobalOnLayoutListener(this);

    int width = view.getMeasuredWidth();

    int height = view.getMeasuredHeight();

    Log.i(TAG, width + " " + height);

  }

});

通过一种增加global listener又移除的方式,获取观察而来的消息。

4.view.measure

手动测绘,分3种情况:

一、match_parent

这个情况是获取不到的。构造这种情况的MeasureSpec需要知道父容器的剩余空间。

二、具体的数值(dp/px)

比如宽高都是100px,可以这样做:

?

1

2

3

4

5

View view = root;

int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);

int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);

view.measure(widthMeasureSpec, heightMeasureSpec);

Log.i(TAG, widthMeasureSpec + " " + heightMeasureSpec);

到这里为止了,这种方法不推荐,因为测出来发现有错误。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值