【问题标题】:How to get position/off-set of an element in android with respect to parent element?如何获取android中元素相对于父元素的位置/偏移量?
【发布时间】:2014-12-26 14:36:56
【问题描述】:

在我的项目中,我的布局如下:

<FrameLayout>   ---------(1)
  <SurfaceView>
     <FrameLayout> ------(2)
  </SurfaceView>
</FrameLayout>

我想访问框架布局(2)相对于框架布局(1)的位置/偏移量。

当我尝试 FrameLayout1.getLeft() 和 FrameLayout1.getTop() 时,我得到它为零。

获取嵌套元素(left,top) 的正确方法是什么?

谢谢!

更新--->

int dpi = getResources().getDisplayMetrics().densityDpi;

int offset1 = childFrameLayoutPosition[0] - rootFrameLayoutPosition[0]; //x offset
int offset2 = childFrameLayoutPosition[1] - rootFrameLayoutPosition[1]; //y offset

      //F1 is child FrameLayout
        newBitmap = Bitmap.createBitmap(bitmap,offset1*w, offset2*w,F1.getWidth()*w,F1.getHeight()*w);

执行此操作后,我得到了 Width 和 Height 参数应该小于位图的宽度和高度的错误。

【问题讨论】:

    标签: android android-layout position android-ui


    【解决方案1】:
    int[] rootFrameLayoutPosition = new int[2];
    int[] childFrameLayoutPosition = new int[2];
    rootFrameLayout.getLocationInWindow(rootFrameLayoutPosition);
    childFrameLayout.getLocationInWindow(childFrameLayoutPosition);
    int offset = childFrameLayoutPosition[1] - rootFrameLayoutPosition[1];
    

    也许我对 x 和 y 感到困惑

    【讨论】:

    • 数组 int[] 中的 index0 给出 x,index1 给出 y。这个解决方案对我有用,谢谢!
    • 我还有一个问题,当我使用这些坐标通过方法进行图像裁剪时:Bitmap.createBitmap(src,int,int,int,int) 裁剪后的图像不是帧布局中指示的部分。我错过了一些 dp 到像素的转换吗?
    • 感谢您的反馈)
    • 位图它的背景或ImageView的src?
    • 对于 ImageView。暂时我只是将裁剪后的图像存储在 SD 卡中。
    猜你喜欢
    • 2012-07-23
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多