【问题标题】:android place a view in a specific place above an imageandroid将视图放置在图像上方的特定位置
【发布时间】:2012-06-26 14:20:43
【问题描述】:

我想创建一个包含图像的布局,我想在其上放置许多图像和 TextView。我知道如何使用 RelativeLayout 将图像放在另一个之上,但是如何以所需的方式对齐它们呢?例如,我希望图像恰好位于我的“背景”图像具有特定黑色圆圈的位置。使用 android:layout_marginTop 等值似乎并不能在每个屏幕上产生效果。

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

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

【问题讨论】:

  • 能否提供“背景”图片

标签: android xml image android-layout android-relativelayout


【解决方案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);
}

【讨论】:

  • 这看起来很有希望,谢谢。您的意思是将这个自定义布局实现为一个扩展布局的类,并将这个类传递给我的 xml 元素?
  • 如果你想使用它的特定元素,你可以覆盖任何布局实现。例如,如果您希望其他Views 使用特定的RelativeLayout 属性(如alignParentLeft),则可能需要覆盖RelativeLayout。如果视图是在 xml 中定义的,那么在布局膨胀时,子级应该已经存在。您只需要一个检索它的系统(getTheChildView() 方法)。
猜你喜欢
  • 1970-01-01
  • 2020-03-26
  • 2018-03-17
  • 1970-01-01
  • 2011-12-31
  • 1970-01-01
  • 2014-02-23
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多