android - fragment : what is the best place to measure Views?

标签 android android-layout android-fragments android-view android-lifecycle

我有一个 fragment ,我需要测量它在屏幕上的 View 的位置/宽度/高度并传递给其他一些类。

所以我有一个函数可以做到这一点,就像这样:

private void measureTest(){
    v = ourView.findViewById(R.id.someTextField);
    v.getLocationOnScreen(loc);
    int w = v.getWidth();
    ...
    SomeClass.passLocation(loc,w);
    ...

问题是 View 的位置/宽度/高度在 fragment 生命周期内没有准备好。 因此,如果我在这些生命周期方法中运行该函数:

onCreateView
onViewCreated
onStart
onResume

我得到错误的位置和宽度/高度测量值或 0 值。 我找到的唯一解决方案是将这样的 GlobalLayoutListener 添加到 mainView

mainView.getViewTreeObserver().addOnGlobalLayoutListener(new     ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
    if(alreadyMeasured)
        mainView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
    else
        measureTest();
}
});

这就完成了工作..但它只是 Yack!海事组织。

有更好的方法吗?似乎是一件很基本的事情

最佳答案

在 fragment 的 onActivityCreated 中检索 currentView(使用 getView())并将一个可运行对象发布到其队列中。在 runnable 内部调用 measureTest()

关于android - fragment : what is the best place to measure Views?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16936494/

相关文章:

java - 底部导航项选定动画 onBackPressed

android - 当子 recyclerview 滚动到最后一项时禁用 ViewPager 分页

android - 在 Android 中加载谷歌地图中的当前位置并不快

android - ActionBarSherlock 在硬件菜单按键上复制操作栏操作

android - 通过样式更改 Android 对话框按钮文本大小

android - 平移、缩放或旋转的 subview 消失

android - 有效数组适配器

android - RxAndroid,如何检测可观察对象是否已完成发射

Android - 如何在布局中存储额外的隐藏信息(按标签)

java - 安卓错误 : Cannot perform this operation because the connection pool has been closed