获取活动中片段的绝对位置

时间:2011-06-01 08:39:46

标签: android android-fragments android-activity android-3.0-honeycomb

我有一个里面有几个片段的活动。我正在为每个片段使用Frame Layout,并将Relative Layout作为父级。

我一直很难获得父母片段的确切位置。但似乎我只能做相对的价值观。

那么,无论如何都要在活动中获得片段的确切位置吗?

1 个答案:

答案 0 :(得分:1)

我没有用Fragments做过这件事但是有片段的内容。 如果您对活动使用findById(),该活动将找到该活动中任何虚增的内容(包括片段内容等)。

然后您可以使用类似View.getLocationOnScreen(int[])的内容,这样可以在屏幕上显示视图的x和y。从来没有在片段上尝试过这个,但如果片段被布局包裹,那么应该没问题。

希望这有帮助吗?

实际上这可能会有所帮助,可能需要更改以接受两个视图,因为此方法位于我自定义的RelativeLayout中:

/**
 * Will return the X,Y of the Anchor view relative to this relative layout.. So It doesn't
 * matter if the anchor view is nested, or any any other layout, this WILL find its location
 * relative too this {@link HelpRelativeLayout}.
 * 
 * @author chris.jenkins
 * @param anchor
 * @return
 */
private int[] calculateAnchorViewPosition(View anchor)
{
    int[] loc = new int[2];
    int[] conLoc = new int[2];
    // getLocationInWindow(conLoc);
    getLocationOnScreen(conLoc);
    // anchor.getLocationInWindow(loc);
    anchor.getLocationOnScreen(loc);

    // get correct top left pos + half the h/w of the anchor
    loc[0] = (loc[0] - conLoc[0]);
    loc[1] = (loc[1] - conLoc[1]);

    MyLog.d(loc[0] + " " + loc[1]);

    return loc;
}