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!