Sunday, 27 June 2021

Android Jetpack Compose - Dynamic layouts

Background

I'm currently investigating options for creating layouts, during the development of the project I'm looking to possibly migrate the UI to Jetpack Compose or post release, depending on the stability/flexibility of the library.

Part of the project will be using a server driven UI. However the twist being the UI is not known ahead of time and will be dynamic (server and data driven).

I have no issues with handling the business logic and presentation layers however when it comes to the UI I will need a requirement to dynamically build the UI based on the presentation data and view models.

TL;DR

With this in mind is it possible to create dynamic layouts (not to be confused with dynamic layout data) using Jetpack Compose?

As a minimal example, with traditional View and ViewGroup this can easily be achieved :

class DynamicViewActivity : AppCompatActivity() {
    
    private lateinit var root : LinearLayout

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)

        // setup view group container
        root = LinearLayout(this)
        root.orientation = LinearLayout.VERTICAL
        root.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, 
            LinearLayout.LayoutParams.MATCH_PARENT)
        
        setContentView(root, LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT))
        
        // some lookup to create a dynamic layout
        val children : List<Pair<View, LinearLayout.LayoutParams>> = getChildren(someArgs)
        
        // add child views
        children.forEach { (view, params) -> root.addView(view, params) }
    }
    
    fun <T : View> addViewToRoot(view: T, params: LinearLayout.LayoutParams) {
        root.addView(view, params)
    }

    fun  removeFromRoot(viewTag : String) {
        root.findViewWithTag<View>(viewTag)?.let(root::removeView)
    }
}

How do you do the same with Jetpack Compose?



from Android Jetpack Compose - Dynamic layouts

No comments:

Post a Comment