I love Compound View

3bdoelnaggar

Abdalla Elnaggar

Posted on June 5, 2022

I love Compound View

I love separating a piece of the UI to a compound view;
first here how to do it.
create the view in xml as normal,

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="40dp"
    tools:parentTag="androidx.constraintlayout.widget.ConstraintLayout"
    android:layout_height="76dp"
    >
    <TextView
        tools:text="سبت"
        android:fontFamily="@font/neo_sans_arabic"
        android:textStyle="bold"
        android:textColor="#FE000000"
        android:id="@+id/dayNameTextView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</merge>
Enter fullscreen mode Exit fullscreen mode

as you see the parent tag is it will take where you gonna inflate it at as its parent.
we create new class that extends ConstraintLayout and infalte it using viewBinding:

class PlanDayView(context: Context, attributeSet: AttributeSet?=null) :
    ConstraintLayout(context, attributeSet) {
    var binding: FoodPlansDayBinding

    init {
        inflate(context, R.layout.food_plans_day, this)
        binding = FoodPlansDayBinding.bind(this)
    }


    fun render(uiDayView: UiDayView) {
           TODO("")
    }

}
Enter fullscreen mode Exit fullscreen mode

then you make a model represent this Compound View:

data class UiDayView(
    val name: String,
    val number: String,
    val progress: Int,
    val isPassedOrToday: Boolean,
    val isFree: Boolean = false,
    val isSelected: Boolean = false,
    val onClick: (UiDayView)-> Unit,
)
Enter fullscreen mode Exit fullscreen mode

Now you can use this in xml like any normal view
or in code by

val view = PlanDayView(context)
Enter fullscreen mode Exit fullscreen mode

here you made a compound and made UiModel for it and separate a piece of the ui.
here is a question how you use this in viewHolder?.

💖 💪 🙅 🚩
3bdoelnaggar
Abdalla Elnaggar

Posted on June 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related