PSLab Android App supports a lot of features and each of these features need components & views for their implementation. A typical UI of PSLab is shown in the figure below. Considering the number of views & components used in the figure, implementation of each view & component separately would lead to a huge volume of repetitive and inefficient code. As it is evident that the EditText and two buttons beside it keep repeating a lot, it is wiser to create a single custom component consisting of an EditText and two buttons. This not only leads to efficient code but also results in a drastic reduction of the volume of code.
Android has a feature which allows creating components. For almost all the cases, the pre-defined views in Android serve our purpose of creating the UIs. However, sometimes there is a need to create custom components to reduce code volume and improve quality. Custom components are used when a particular set of component needed by us is not present in the Android view collection or when a pattern of components is frequently repeated or when we need to reduce the code complexity.
The above set can be replaced by defining a custom component which includes an edittext and two buttons and then treating it like just any other component. To get started with creating a custom component, the steps are the following:
Create a layout for the custom component to be designed
The layout file edittext_control.xml is created with three views and each one of them has been assigned an ID along with all the other relevant parameters.
Incorporate the newly created custom layout in the Activity/Fragment layout file
The custom layout can be added the activity/fragment layout just like any other view and can be assigned properties similarly.
Create the activity file for the custom layout
In the activity file Editextwidget.java, the views of the custom layout are defined and functionalities are assigned to them. For example, here there are two buttons which work as increment/decrement buttons and an edittext which takes numeric input. The buttons are initiated just like the way they are done in other activity/fragment using OnClickListener.
Define the attributes for the custom layout
The attributes for the custom layout are defined in the attrs.xml file. Each attribute is assigned a name and a format which can be int, float, double, string etc.
Finally call the methods of the custom layout from the desired activity/fragment
The init method of Edittextwidget.java is called while passing the relevant parameters like context, least count, maxima and minima.
Additional Resources on Custom Components
- Official Android Guide on Custom components – https://developer.android.com/guide/topics/ui/custom-components.html
- Simple example of creating a custom component to get started – https://www.tutorialspoint.com/android/android_custom_components.htm