Android RelativeLayout:显示ConstraintLayouts的列表

时间:2019-02-04 15:34:48

标签: android list android-relativelayout layoutparams

我有一个名为ConstraintLayout的{​​{1}}文件,其中包含显示R.layout.new_plan对象所需的视图。我想在PlanItem根视图中显示 {strong} 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以某种方式使用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)
}

这确实显示了所有PlanItem,但它们显示在彼此的顶部,而不是显示在底部。

enter image description here

enter image description here

如何按顺序显示计划项目视图,而不是一起整理?

1 个答案:

答案 0 :(得分:0)

我需要做的关键是将planItemView id 设置为我的应用中从未使用过的ID。因此我创建了一个不太可能被其他视图使用的数字常数,并将其用作第二,第三,第四等计划项目视图的基础。

此后,RelativeLayout根目录正确显示了单个plan item view

  1. 添加到班级顶部

    companion object {
        private const val BASE_PLAN_ITEM_ID = 164
    }
    
  2. 更新方法

    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)
    }