Search code examples
androidperformanceandroid-databindingandroid-inflatemaintainability

Changing edit screen according to selected item in recycler view


I have flow like below

recyclerview --- click on item ---> detail screen --- click on edit option menu item ---> edit screen

Here fields show in edit screen changes based on the recyclerview item user clicked. I am using databinding in my project, so there two ways to handle this situation.

  • Inflate all the views in edit screen in a single layout and set visibility of views to View.GONE based on the item clicked
  • Use separate fragments for each edit screen.
    • Pro: Heap is not allocated for unused views
    • Con: multiple fragments, layouts

Which is better in terms of performance, code maintainability? Are there any other approaches?


Solution

  • First of all the better approach is to use separate fragment. It will help to separate the code and maintain it easily with less lines. You can also create BaseFragment for common methods to make code cleaner and less in the fragment.

    On the other hand if you used the View Visible and Gone method than heap issue. You can less this issue to add view dynamically.

    You can take a empty container and based on your condition add the view. You have to create separate layout file for each view.

    Add Empty Container

                     <FrameLayout
                        android:id="@+id/container"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintHorizontal_bias="0.0"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toTopOf="parent" />   
    

    Add the view dynamically

     val view = inflater.inflate(
                            R.layout.file_name, null)
    container.addView(view)
    

    So that you don't need to hide or show to view based on condition. You just have to add view as per your requirement.

    But you have to code for both the layout in one file.

    For Data Binding :

    val view = inflater.inflate(
                            R.layout.row_article_home, null)
                    val binding = DataBindingUtil.bind<RowArticleHomeBinding>(view)!!
    binding.arg = "xyz"
    container.addView(view) or container.addView(binding.rootView)
    

    Row Article View

    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">
    
        <data>
          <variable
                name="arg"
                type="String" />
        </data>
    
    <androidx.cardview.widget.CardView/>
    
    </layout>