There are times when we create UI for apps, some component being repetitively used in more than one layout. In that case, it is more logical if we created Custom View class on Android, hence the view can be used repetitively on other layout, rather than copy paste the XML code.
On this article, I will try to explain step by step to create Custom View class with the attributes that can be modified from XML code or programmatically.
The layout study case will be to create order summary as bellow. All the text view for Origin, Destination, Pickup Date, Pickup Time, Load Size and Load Type will be using our Custom View class

- Create layout for Custom View
Create new Layout res file on res/layout folder named it as custom_view.xml. This layout will be layout of our Custom View. You can copy paste from my layout below or style it your self.
2. Create attributes
The next step we will create attribute for label_text and content_text. With this attributes, we can modified the content of our TextView from xml Layout or from Activity class.
Create new Values resource file at res/values folder and named it as attrs.xml
3. Create Custom View class
- Create java class that extends FrameLayout class or View class (Line 1)
- Inflate the costum_view.xml layout that we have been created on step 1 (Line 15)
- Create reference for attributes which its content will be modified later (Line 17 & 18)
- (Line 20–30) This line explain that the attributes can be modified directly from xml code.
- If necessary, create setter so that the attributes content can be modified programmatically (Line 41 & 45)
4. Create Activity and Layout
At this point, our prep work is done. Our Custom View class is ready. Now we only need to create layout and activity for the apps.
As you can see, we can modified the view content from our xml code now. Line 34, 43, 58, 66, 81 & 89 set the label text from xml code with attribute app:label_text. While line 33 & 42 set content text with attribute app:content_text.
Below is the Activity class corresponding with the layout that we just made. We will set content_text programmatically from this activity.
5. Modified Attributes
As explained on previous point we have designed CustomView class in such a way so that the TextView content (label_text & content_text) can be set from Layout xml class or Activity java class.
Point no 4 has shown how to modified the attribute content from Layout xml class. To modified the attribute content from java class, we need to called the setter method from CustomView class.
Add this code unto the OrderSummaryActivity.class
If you following all the step, run the app and it will shown fine. The complete code can be found here.
If this article help you on understanding the CustomView in a better way, please give me clap.