我有一个自定义的xml文件。我想在一个布局(比如说相对)中动态地(显然)重复n次。
我看过很多帖子,但没有一篇有用。我不是在找一个ListView
或Adapters
左右的。它就像-aRelativeLayout
一样简单。在其中,将自定义xml逐个添加。任何次数。
使用静态LinearLayout
(垂直方向),动态添加视图会导致渲染一次,而不是一次呈现在另一次之下。不知道为什么。尽管aTextView
左右在aLinearLayout
内的一个循环中重复一个在另一个下面(垂直)。
然后我动态地创建了布局(相对的),并扩展了自定义xml。显示了一个。当我尝试在第一个下面再找一个时,它告诉我先删除孩子的父母(例外)。如果我这样做并再次添加,就相当于删除第一个渲染视图并再次添加它。
那么如何在同一布局中获得多个视图呢?
对我所做尝试的粗略介绍:
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
(水平)中添加动态视图,则它们将与添加到视图中的新创建实例一起水平显示。
然而,令人震惊的是,在LinearLayout
(垂直方向)的情况下,情况并不相同。因此整个混乱。
解决方案:
布局文件与变量绑定在一起,有点像这样:
customLay = (RelativeLayout) mainLay.findViewById(R.id.dynamicCustomLayout);
然后,创建一个
RelativeLayout
,在其中添加/包装前一个变量。customLayout = new RelativeLayout(this);
customLayout.addView(customLay);
每个布局都分配了一个ID:
customLayout.setId(i);
然后运行一个循环(如果i=0且i>0的条件为2)
对于i>0(表示要添加到第一个动态布局下面的第二个动态布局),将创建
Dynamic RelativeLayout
:params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
然后,对于i>0,使用动态视图的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);
}
然后添加到主根布局,其中需要显示所有这些视图或卡:
includeLayout.addView(customLayout);
当然,代码不仅仅是这个。我已经写了一些基本的要点,帮助我达到目标,并可能在未来帮助其他人。
所以主要的本质是---
使用
LayoutParameter
,以绑定static
Dynamic RelativeLayout
,然后将id分配给
RelativeLayout
包装器,以及根据ids,使用
Dynamic RelativeLayout
来放置比以前的要低。