安卓的RelativeLayout:显示ConstraintLayout列表

问题描述 投票:0回答:1

我有一个名为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 PlanItems,并将其添加使用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,但它们显示在彼此的顶部,不会下到谷底。

enter image description here

enter image description here

我怎样才能显示,以计划项目的意见下去,不嘎吱嘎吱在一起呢?

android list android-relativelayout layoutparams
1个回答
0
投票

那我需要做的事情的关键是将planItemView ID设置为从来没有在我的应用程序中使用的ID。所以我创造了一些常数,不太可能被其他浏览使用,并把它作为第二,第三,第四等计划项目视图基地。

在此之后,RelativeLayout根被正确地示出了个人plan item view

  1. 添加到类的顶部 companion object { private const val BASE_PLAN_ITEM_ID = 164 }
  2. Update方法 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) }
© www.soinside.com 2019 - 2024. All rights reserved.