1

假设我在 xml 文件中创建了一个相对布局,并在此布局中的某个位置放置了一个占位符以供将来查看。这个未来视图是另一个 XML 视图中的另一个布局。如何在代码中做到这一点?我知道我必须膨胀未来视图,但是当我将它添加到主布局时,它最终成为左上角的核心,而不是我为它创建的占位符谢谢

4

2 回答 2

1

忘记占位符,只需像正常一样添加视图并在创建时指定所需的参数。

View v = layoutInflater.inflate(R.layout.future_view, null);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
v.addRule(RelativeLayout.ALIGN_WITH_PARENT_TOP);
relativeLayout.addView(v,relativeParams)
于 2012-04-10T02:23:49.393 回答
1

您可以将任何视图添加到布局中的任何位置,将视图的父视图作为RelativeLayout,假设您要将视图放置在屏幕上的(x,y)点,通过方法找出布局在屏幕上的位置:

View.getLocationOnScreen()

假设我们通过这种方法得到 x1 和 y1。现在通过视图的绝对 x, y 坐标 - 父级的绝对 x1, y1 找出视图相对于父布局的未来 (x, y) 位置。让我们假设我们发现差异为 x2,y2。

现在定义视图的 LayoutParams,如下所示:

    View v = layoutInflater.inflate(R.layout.future_view, null);
    RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
   params.setMargins(x2, y2, 0, 0);


    relativeLayout.addView(v,relativeParams)
于 2012-04-10T04:46:19.247 回答