首页 > 系统 > Android > 正文

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

2019-10-22 18:15:40
字体:
来源:转载
供稿:网友

借鉴自开发艺术

1.onWindowFocusChanged

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

@Overridepublic void onWindowFocusChanged(boolean hasFocus) {  super.onWindowFocusChanged(hasFocus);  if (hasFocus) {    int width = view.getMeasuredWidth();    int height = view.getMeasuredHeight();  }}

2.view.post

@Overrideprotected 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方法将被回调。

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,可以这样做:

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);

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

以上这篇Android中获取控件宽高的4种方法集合就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表