Tuesday 8 August 2017

Android Custom Views with Examples

Android Custom Views

Some times we need very personalized views or you can say very personalized behavior of the android views. For this purpose android provides the support for the custom views. We can create our own views and define there behavior as our needs.
If we just need to make the little adjustments to the existing views like Button, EditText, ListView, Layouts or any other view, we can simply do that by extending the predefined view to our own classes and change there characteristics.

Use Case

Some of the example use cases for custom views are as follows:
  • A control with some predefined images.
  • Group of perdefined views to use throughout our app.
  • Change look and feel of predefined views.
  • Custom behavior on onClick(), onFocusChanged(), onLongPressed() etc. events.

@Override

You can override a list of method of the views after extending them to your own class you change there behavior. You can override
  • onDraw()
  • onMeasure()
  • onKeyDown()
  • setMeasuredDimension(int width, int height)
and many more methods. Now your methods will be called instead of the parent class on the specified events. All you have to do is use your own class name in the XML to use them and provide there attributes.

Example

For an example, we will create our own image view which shows the square images rather than the original dimension of the image. For this purpose, all we have to do is just extend the imageView class to our own class and define the custom behavior. following is the code for the class.

SquareImage.java
Now to use this class, all you have to do is
Similarly, if you want to change the font of all the EditTexts of your app, you just need to extend the already existing Edittext with you class and change the font style. You can find the class as follow:

CustomEditText.java

You can a sample application with two different custom components at Github Repository. All you need to do is create res/values/attr.xml. Then create the layout xml file with the the view in res/layout. And finally write the java class to inflate the view and set the values for the views. You are done! Just enjoy using the component.
If you still get the error feel free to comment below or contact me at farooqahmadkhan003@gmail.com. Happy Coding!!

1 comment:

  1. This comment has been removed by a blog administrator.

    ReplyDelete