gpt4 book ai didi

android - 在布局中多次添加自定义 View

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:47 26 4
gpt4 key购买 nike

我有一个自定义 XML 文件。我想在布局(比如相对)中动态地(显然)重复 n 次。

我看了很多帖子,但没有一个有用。我不是在寻找 ListViewAdapters 之类的东西。它就像一个 RelativeLayout 一样简单。在其中,将自定义 XML 一个添加到另一个之上。任意次数。

使用静态 LinearLayout(垂直方向),动态添加 View 会导致渲染一次,而不是一个在另一个下面。不知道为什么。尽管 TextView 左右会在 LinearLayout(垂直)内的循环中逐个重复。

然后我动态创建了布局(相对),并扩充了自定义 XML。显示一个。当我在第一个下面尝试另一个时,它告诉我先删除 child 的 parent (异常(exception))。如果我这样做并再次添加,它与删除第一个渲染 View 并再次添加它一样好。

那么如何在同一布局中获得多个 View ?

我尝试过的粗略介绍:

 mainLayout = (RelativeLayout)findViewById(R.id.mainlay); //Mainlayout containing some views already

params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW,R.id.sideLayout); //sideLayout is an existing LinearLayout within the main layout.



View child = getLayoutInflater().inflate(R.layout.dynamiccustomlayout,null);

RelativeLayout r1 = new RelativeLayout(this);

r1.setLayoutParams(params);
r1.addView(child);
mainLayout.addView(r1);
mainLayout.setLayoutParams(params);
mainLayout.addView( child);
/* r2 = new RelativeLayout(this);
r2.setLayoutParams(params);
r2.addView(contentLayout); [Gives exception] */

最佳答案

这就是我的结果......

在此之前,android 的问题是:

如果您在 LinearLayout(水平)中添加动态 View ,它们将与新创建的实例一起水平显示,添加到 View 中。

然而,令人震惊的是,在 LinearLayout(垂直方向)的情况下却不一样。因此,整个困惑。

解决方案:

RelativeLayout 布局文件与变量绑定(bind),有点像这样:

customLay = (RelativeLayout) mainLay.findViewById(R.id.dynamicCustomLayout);

然后,创建了一个 Dynamic RelativeLayout,其中添加/包装了之前的变量。

customLayout = new RelativeLayout(this);
customLayout.addView(customLay);

每个布局都分配了一个 id:

 customLayout.setId(i);

然后运行一个循环(如果 i=0 且 i>0 的条件为 2)

对于 i>0(表示第二个动态布局,将添加到第一个动态布局下方),创建 LayoutParameter:

params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

然后对于 i>0,使用动态 View 的 id,将它们一个一个地添加到另一个下方:

//Following code below used id to place these views below each other to attain list type arrangement of views//

// i==0 for first view on top//
if (i == 0) {
params.addRule(RelativeLayout.BELOW, R.id.sideLayout);
customLayout.setLayoutParams(params);
}
// i>0 for views that will follow the first top//
else {
params.addRule(RelativeLayout.BELOW, i - 1);
customLayout.setLayoutParams(params);
}

然后添加到主根布局,其中需要显示所有这些 View 或卡片:

includeLayout.addView(customLayout);

当然,代码不止这些。我已经写下了帮助我实现目标的要点,将来可能会对其他人有所帮助。

所以主要的本质是---

  1. 使用Dynamic RelativeLayout
  2. 绑定(bind)静态RelativeLayout,以及
  3. 将 id 分配给 Dynamic RelativeLayout 包装器,以及
  4. 根据 id 使用 RelativeLayoutParameters 放置以下内容ID 低于之前的 ID。

关于android - 在布局中多次添加自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33209634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com