从片段测量视图

时间:2015-03-03 19:05:07

标签: android android-fragments

所以,我有一个片段,其中有两个按钮。 我想在这个片段中获得此按钮位置。所以,我试图这样做:

Button button;
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        final View w = inflater.inflate(R.layout.fragment_buttons, container, false);
        button = (Button)w.findViewById(R.id.button);
        final ViewTreeObserver obs = button.getViewTreeObserver();
        obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw () {
                Rect r = locateView(w.findViewById(R.id.button));

                return true;
            }
        });
        return w;
    }

这就是我获得按钮位置的方式

public  Rect locateView(View view) {
    Rect loc = new Rect();
    int[] location = new int[2];
    if (view == null) {
        return loc;
    }
    view.getLocationOnScreen(location);

    loc.left = location[0];
    loc.top = location[1];
    loc.right = loc.left + view.getWidth();
    loc.bottom = loc.top + view.getHeight();
    return loc;
}

然而,问题是永远不会调用onPreDraw。我做错了什么?

1 个答案:

答案 0 :(得分:1)

我刚刚想出如何解决这个问题。

 button = (Button)w.findViewById(R.id.button);
        ViewTreeObserver observer = button.getViewTreeObserver();
        observer.addOnGlobalLayoutListener (new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = locateView(button);
                button.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

此代码正常运行。但是,我仍然不知道为什么以前的版本没有用。

相关问题