Android 分段测量视图

Android 分段测量视图,android,android-fragments,android-lifecycle,Android,Android Fragments,Android Lifecycle,我需要知道图像视图的宽度和高度。有没有一种方法可以测量它的碎片?在标准活动中,我使用以下方法: @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); image.getWidth(); image.getHeight(); } 但是在哪里可以使用image.getWidth()和image.getHeight()在片段中?使

我需要知道图像视图的宽度和高度。有没有一种方法可以测量它的碎片?在标准活动中,我使用以下方法:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    image.getWidth();
    image.getHeight();
}
但是在哪里可以使用
image.getWidth()
image.getHeight()在片段中?

使用。您可以在
onCreateView()
中将侦听器分配给您的
ImageView
,就像您在链接中的回答一样。对于主活动,它也比onWindowFocusChanged()更可靠,因此我建议使用切换策略

编辑

例如:

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

为了补充这个答案。。。我试图使用这个片段获取ActionBar选项卡侦听器显示的片段中ImageView的宽度和高度。(使用support.v4api,针对API14+)我必须将代码片段放入“onViewCreated”方法(?)中才能得到结果。事实上,在“onCreateView”中,testView对象为null,找不到视图,这导致了异常。不过,您应该能够将其应用于在onCreateView中返回的视图。它返回null的原因是,
profileContainer
还不存在。什么是profilePadding和profileContainer类型?@stealthrabi它们都是
View
对象,或者是从
View
@DeeV派生的任何对象。这对profilePadding和profileContainer类型不是一个很好的解释。