【问题标题】:Getting absolute location of a fragment in an activity在活动中获取片段的绝对位置
【发布时间】:2011-06-01 08:39:46
【问题描述】:

我有一个活动,里面有几个片段。我为每个片段使用框架布局,并将相对布局作为父级。

我一直在为获取父片段的确切位置而头疼。但似乎我只能相对值。

那么,有没有办法在活动中获取片段的确切位置?

【问题讨论】:

  • 您为什么需要这些信息?在 Android 上要避免绝对定位。
  • 我想将它与动画师一起使用

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


【解决方案1】:

我没有对 Fragments 进行此操作,而是对 Fragments 的内容进行了此操作。 如果您在 Activity 上使用 findById(),它将找到该 Activity 中任何膨胀的 id(包括片段内容等)。

然后您可以使用 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    相关资源
    最近更新 更多