相关文章推荐
呐喊的生姜  ·  Day07 - [豐收款] ...·  11 月前    · 
深情的小刀  ·  Databricks Runtime ...·  2 年前    · 

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

3 人关注

在我的 FragmentLayout 中我有一个 LinearLayout 和多个子视图( TextView CardView )。我想找到所有 LinearLayout 视图的顶部偏移,但我总是得到零。
This is my code:

@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>
    
android
view
nestedscrollview
Kapta
Kapta
发布于 2016-06-13
2 个回答
Neo
Neo
发布于 2022-06-07
已采纳
0 人赞同

onWindowFocusChanged(boolean hasFocus) 方法中写出查找位置的函数,或在处理程序中发布任务,并有100毫秒的延迟。

我是一个活动或片段的外置,我怎么做?
Neo
尝试一下,新处理程序().post(...... v.getLocationOnScreen(location); .....)中的代码。
如何在onBindView中使用这个功能?
basileus
basileus
发布于 2022-06-07
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);