如何在相对布局或任何布局中动态添加视图

How can I add Views dynamically in a Relative layout or in any Layout

嗯,我的问题有点复杂(对我来说)。 假设我有一个 RelativeLayout(或任何其他需要的 Layout)。

现在我做了一些 View,比如 TextView。(多个 View)。 那些 View 将包括我将从 java 代码中给出的以下特征。

  1. 我想将 View 添加到布局的特定位置。
  2. 两个或更多View可以重叠(如下图)
  3. 它是一种 AddView(child, positionX, width, height);我知道没有这样的方法。但我需要一个。

其中 positionX 将是一个整数,用于定义 View 将设置在 Layout 从顶部开始的位置。

现在我想将那些 View 添加到 Layout 中,如下图所示。

(所有 View 均为矩形;抱歉编辑不当。)

我该怎么做? 我非常需要解决方案。

我希望我已经用我糟糕的英语解释了我的问题:(

提前谢谢你 <3 <3

正如你所说,

All View will be of rectangular size

所以让我们以一个按钮yourButton为例。您需要传递两个值,一个来自顶部,一个来自您要放置视图的左侧。然后使用下面的方法,如你所愿 addView()RelativeLayout 中实现所需的输出:

private void addView(child, positionFromTop, positionFromLeft, width, height) {
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.topMargin = (int)(positionFromTop);
    layoutParams.leftMargin = (int)(positionFromLeft);
    yourButton.setLayoutParams(layoutParams);
}

如果需要,您可以以类似的方式以编程方式使用宽度和高度自定义布局。请参考此 answer 以获取如何以编程方式调整自定义视图大小的代码。希望对您有所帮助!

试试这个:

//-----Main Layout-----\
LinearLayout l1 = findViewById(R.id.myLinear);
ll.setOrientation(LinearLayout.VERTICAL);

//-----First layout-----\
LinearLayout l11 = new LinearLayout(this);
l11.setBackgroundColor(android.R.color.holo_orange_dark);
l1.addView(l11, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

//-----Second layout-----\
LinearLayout l12 = new LinearLayout(this);
l12.setBackgroundColor(android.R.color.holo_green_dark);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(-30, 20, 20, 0); //Negative margin top to superposition views
l1.addView(l12, layoutParams);

如果您想动态添加多个视图,可以尝试将它们重构为一个复合视图(放置它们会更容易)

https://www.vogella.com/tutorials/AndroidCustomViews/article.html

您使用什么类型的 ViewGroup?如果它的约束布局,您可以使用 ConstraintLayout.LayoutParams 以与 SaadAAkash 提到的相同方式以编程方式设置约束

您也可以使用 FlexBox layout provided by google to add view dynamically. You can check this Medium post 来清楚地了解 Flexbox 布局