Search code examples
javauser-interfacecode-duplication

Avoid duplicating UI codes


I want to write new UI class which contain Check box and Label. At the moment there is existing UI class with same elements but their element descriptions are different. But data model for both UIs are going to be same.

So is it good practice to keep separate UI classes (by duplicating GridBagConstraints and other stuffs) for each or move common code in to abstract layer and derive description of the UI elements in the implementation level?


Solution

  • There are some other things that you can try, so you can avoid duplicating UI code, I'll give you 2 examples:

    1. You can use the tag to bring the UI code inside another layout file and show it in you current layout, at the end you will be able to call it directly from your current Activity or Fragment in the same way you do with the other elements at the root of your Fragment or Activity class.

    Re-using layouts

    First layout file named: include_example_layout.xml

    <merge xmlns:android="http://schemas.android.com/apk/res/android">
    
        <TextView
            android:id="@+id/textView_includeExampleLayout_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
        <CheckBox
            android:id="@+id/checkBox_includeExampleLayout_valid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    </merge>
    

    Second layout file named: activity_main.xml

    <LinearLayout>
    
        <include layout="@layout/toolbar_search_algolia"/>
    
    </LinearLayout>
    

    And from the MainActivity file you will be able to call the ids of this file include_example_layout as if they were declared directly in your activity_main file, so you will be able to reuse it.

    1. The second one is creating a View element, this has an added advantage to the first method but is a little more complex, the thing is that you will be able to move some UI logic to the class of the new View element, for example if you want to disable the checkbox when something is happening with the information you can move thtat logic to the new view class.

    Custom View

    I'll no write a complete tutorial about this because it is a extense topic but I'll left some examples in other places that will help you understand the most basic concepts, there are two way in wich you can build CustomViews the first one is extending the View class that will force you to create it from scratch, but you can also extend other Views like a LinearLayout and this will help you to get started with the concept of a CustomView (is not recommended in every case, it can slow down your UI if you don't use it wisely)

    Example extending LinearLayout

    Example extending View