测量视图片段 [英] Measure view in fragment

查看:138
本文介绍了测量视图片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道ImageView的宽度和高度。有没有一种方法来衡量它的片段?在标准的活动我用这样的:

I need to know ImageView width and height. Is there a way to measure it in fragment ? In standard Activity I use this :

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    image.getWidth();
    image.getHeight();
}

不过,我在这里可以使用 image.getWidth(); image.getHeight(); 的片段?

推荐答案

使用的<一个href="http://stackoverflow.com/questions/4142090/how-do-you-to-retrieve-dimensions-of-a-view-getheight-and-getwidth-always-r">GlobalLayoutListener.您可以在 onCreateView分配监听到你的的ImageView ()就像你在链接答案做。它也比 onWindowFocusChanged()为主体的活动,所以我建议切换策略。

Use the GlobalLayoutListener. You assign the listener to your ImageView in onCreateView() just like you do in that answer in the link. It also is more reliable than onWindowFocusChanged() for the main Activity so I recommend switching strategies.

修改

例如:

final View testView = findViewById(R.id.view_id);
ViewTreeObserver vto = testView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
  @Override
  public void onGlobalLayout() {
    Log.d("TEST", "Height = " + testView.getHeight() + " Width = " + testView.getWidth());
    ViewTreeObserver obs = testView.getViewTreeObserver();
    obs.removeGlobalOnLayoutListener(this);
  }
});

这篇关于测量视图片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆