android将视图放在图像上方的特定位置

时间:2012-06-26 14:20:44

标签: android xml image android-layout relativelayout

我想创建一个包含图像的布局,我想在其上放置许多图像和TextView。我知道如何使用RelativeLayout将图像放在另一个上面,但是如何以期望的方式对齐它们?例如,我希望图像准确地位于我的“背景”图像具有特定黑色圆圈的位置。使用像android:layout_marginTop等值这样的值似乎并没有在每个屏幕上都有效。

那么处理这些问题的正确方法是什么?

编辑: 我无法上传图片,但我在这里上传了一个非常简单的草图: http://imageshack.us/photo/my-images/715/buttonlayout.png/ 所有按钮都有图标和文字(必须是文本视图,以便我可以根据需要以编程方式更改它)

1 个答案:

答案 0 :(得分:1)

您必须创建一个自定义布局,将图像专门放置在您希望它们相对于父视图大小的位置。如果您选择,则可以覆盖LayoutParams并将自定义属性应用于它们,以便自定义视图进行阅读。

无论如何,要专门放置一个项目,例如从顶部向下30%,从左侧向下20%,您将覆盖onLayout()

@Override
public void onLayout(boolean c, int left, int top, int right, int bottom) {
    super.onLayout(c, left, top, right, bottom);

    int width = right - left;
    int height = bottom - top;

    View v = getTheChildView();
    int viewL = left + (int)(width * .2f); // The left pixel is 20% down the total width of the parent view
    int viewR = viewL + v.getWidth(); // The right pixel is the left pixel plus the measured width of the child view itself
    int viewT = top + (int)(height * .3f); // The top pixel is 30% down the total height of the parent view
    int viewB = top + v.getHeight(); // The bottom pixel is the top pixel plus the measured height of the child view itself   
    v.layout(viewL, viewT, viewR, viewB);
}