2

I have many activities in my application. Each activity has many UI elements like EditText, TextView, DatePicker, DropDown etc. Activity has both static components (views statically placed in xml layout) and dynamic components (views added at runtime based on business logic and API response). The UI elements to be added in activity are dynamic. What all UI elements needs to be added, depends on the API response.

I'm thinking about writing a method which takes in the information about what all views to be added as parameter and constructs the view and return it as a LinearLayout with all child views added.

In the code snippet below, rowBuilder is a data class which stores information about the views to be added at runtime. The method will build a vertical linearLayout with all the views needed and return it.

fun getUIFields(context: Context, rowBuilderList: ArrayList<RowBuilder>): LinearLayout {
    val rootVerticalLinearLayout: LinearLayout = getRootVerticalLinearLayout(context)

    for(i in 0 until rowBuilderList.size) {
        val horizontalLinearLayout = getHorizontalLinearLayout(context)
        for (j in 0 until rowBuilderList[i].columnBuilderList.size) {
            val formFieldInfo = rowBuilderList[i].columnBuilderList[j].formFieldInfo
            if (formFieldInfo.formFieldType == FormFieldType.EDIT_TEXT) {
                addEditText(formFieldInfo, horizontalLinearLayout, context, i.toString() + j.toString())
            } else if (formFieldInfo.formFieldType == FormFieldType.DATE_PICKER) {
                addEditTextForDatePicker(formFieldInfo, horizontalLinearLayout, context, i.toString() + j.toString())
            }
        }
        rootVerticalLinearLayout.addView(horizontalLinearLayout, i)
    }
    return rootVerticalLinearLayout
}

Where do I place the above logic, which requires context? I know we have AndroidViewModel, wherein I can use context. Also, If I write the above logic in ViewModel, the same code needs to be duplicated in every viewmodels. I need to know about a more efficient approach using MVVM

Please help!

Rakesh
  • 1,205
  • 1
  • 14
  • 33
  • first I would place this piece of code in activities/fragments. I don't see any reason why it would be in viewmodel. And second, maybe you could make this function an Activity extension in order to reuse it? – gts13 Jun 21 '21 at 08:52

0 Answers0