为什么getLocationOnScreen(location)总是返回0?

3
在我的FragmentLayout中,我有一个包含多个子视图(TextViewCardView)的LinearLayout。我想找到所有LinearLayout视图的顶部偏移量,但总是得到零。
这是我的代码:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_detail, container, false);

    nestedScrollView = (NestedScrollView) view.findViewById(R.id.nestedScrollView);
    linearLayout = (LinearLayout) view.findViewById(R.id.lll);

    int childCount = linearLayout.getChildCount();
    int[] location = new int[2];
    for (int i = 0; i < childCount; i++) {
        View v = linearLayout.getChildAt(i);
        v.getLocationOnScreen(location);

        Log.e("locX", location[0] + "");
        Log.e("locY", location[1] + "");

    }


    return view;
}

以下是我的布局xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.CoordinatorLayout>
        <android.support.design.widget.AppBarLayout>
            <android.support.design.widget.CollapsingToolbarLayout>              
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/nestedScrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <LinearLayout android:id="@+id/lll">

            // views are there 

            </LinearLayout>


        </android.support.v4.widget.NestedScrollView>
    </android.support.design.widget.CoordinatorLayout>
</LinearLayout>
2个回答

5

编写函数来查找onWindowFocusChanged(boolean hasFocus)方法中的位置或将任务发布到具有100毫秒延迟的处理程序。


我在活动或片段之外,我该怎么做? - suulisin
尝试在新的Handler()中使用post()方法来执行代码,其中包含v.getLocationOnScreen(location)。 - Neo
如何在 onBindView 中利用这个? - Nouman Ch

0

在调用onCreate()时,您的屏幕尚未准备好。要获取屏幕的所有数据,您需要等待它完全完成。您可以使用:

your_main_layout_here.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
                        // Remove the Global observer once it is called
        your_main_layout_here.getViewTreeObserver().removeOnGlobalLayoutListener(this);

        // Your code here, i.e. check the view's location
        }
    });

然后


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接