我有一个名为ConstraintLayout
一个R.layout.new_plan
文件,其中包含显示PlanItem
对象所需的意见。我想在R.layout.new_plan
根视图中显示RelativeLayout
的列表。
我的父母RelativeLayout
/根的就像这样:
<RelativeLayout
android:id="@+id/rl_plan_items"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<!-- other properties here -->
</RelativeLayout>
换句话说,我有一个List<PlanItem>
和我想显示该列表,使用R.layout.new_plan
视图以显示每个PlanItem
,在rl_plan_items
。我现在做的方法是进行循环列表中的每个PlanItem
,根据当前TextView
的属性中设置R.layout.new_plan
PlanItem
s,并将其添加使用rl_plan_items
以某种方式RelativeLayout.LayoutParams
。
该代码是这样的:
private fun PlanItem.addToRootView(rootView: RelativeLayout, pos: Int) {
val planItemView: ConstraintLayout = inflater
.inflate(R.layout.new_plan, rootView, false) as ConstraintLayout
planItemView.id = pos
with(planItemView) {
tv_title.text = name
tv_desc.setTextAndGoneIfEmpty(description)
tv_date.text = getDateToDisplay(resources)
tv_subject.setTextAndGoneIfEmpty(subject?.name)
}
val params = planItemView.layoutParams as RelativeLayout.LayoutParams
val idOfBelow: Int = if (pos > 0) planItemView.id - 1 else rootView.id
params.addRule(RelativeLayout.BELOW, idOfBelow)
rootView.addView(planItemView, params)
}
在我的片段:
for (i in planItems.indices) {
planItems[i].addToRootView(rl_plan_items, i)
}
这确实显示所有PlanItems,但它们显示在彼此的顶部,不会下到谷底。
我怎样才能显示,以计划项目的意见下去,不嘎吱嘎吱在一起呢?
那我需要做的事情的关键是将planItemView
ID设置为从来没有在我的应用程序中使用的ID。所以我创造了一些常数,不太可能被其他浏览使用,并把它作为第二,第三,第四等计划项目视图基地。
在此之后,RelativeLayout
根被正确地示出了个人plan item view
。
companion object {
private const val BASE_PLAN_ITEM_ID = 164
}
private fun PlanItem.addToRootView(
rootView: RelativeLayout,
pos: Int,
r: Resources
) {
val planItemView: ConstraintLayout = inflater
.inflate(R.layout.new_plan, rootView, false) as ConstraintLayout
planItemView.id = BASE_PLAN_ITEM_ID + pos
with(planItemView) {
tv_title.text = name
tv_desc.setTextAndGoneIfEmpty(description)
tv_date.text = getDateToDisplay(resources)
tv_subject.setTextAndGoneIfEmpty(subject?.name)
}
val params = planItemView.layoutParams as RelativeLayout.LayoutParams
val idOfBelow: Int
if (planItemView.id > BASE_PLAN_ITEM_ID) {
idOfBelow = planItemView.id - 1
// If it is the 2nd or more item in the list, add a margin above it
params.setMargins(
params.leftMargin,
calculatePx(16, r),
params.rightMargin,
params.bottomMargin
)
} else {
idOfBelow = rootView.id
}
params.addRule(RelativeLayout.BELOW, idOfBelow)
rootView.addView(planItemView, params)
}