Customview in Android

Tram Ho


Sometimes in Android you have a layout to use in a few different places and only a few small changes. For those cases we should create our own Custom View. It will save us time. Basically we just need to create custom view in one place and then call out when near. Also edit the required arrtibute.

Why not use <include>?

Because simply when we use include, we are not able to pass parameters. As such, Include is only useful in cases where the layout does not change in different places.

Let’s code

Next I will guide you how to inflate into a layout that you have created earlier. And pass 2 parameters to edit that layout. The image above is the layout that we will conduct custom. Our desire is to be able to reuse this view elsewhere. And it is possible to change images and text via attributes that we define ourselves.

Let’s create a custom custom layout, here I named custom_view:

Follow them in the values ​​folder. We create the file called attrs.xml . If you already have one, skip this step.

Inside this file we create the <declare-styleable … tag

  1. You should name the declare-styleable tag the same name as the class you plan to do custom. In this case, it is CustomView
  2. Create an attr tag for the custom parameter you want. Now let’s create the CustomView class:

  1. The constructor will take two parameters, Context and AttributeSet. Our class will inherit an existing view, maybe LinearLayout, RelativeLayout. Or a certain view of your choice.
  2. We will refer to the views via id.
  3. We assign the attributes variable to the styleable we created in the atrrs.xml file
  4. We set values ​​for image and text by anotation: R.styleable.CustomView_image and R.styleable.CustomView_text .
  5. Finally, recycle the attributes. This is necessary for android memory management.

At this point, we are almost done creating customview. Now we can use our customview like another regular View:

Note that when using customview we have to add xmlns:app=" to the root layout to be able to call the custom attributes we created.

The layout after we add the newly created customview will be as follows:

Note that if the layout does not appear the first time, we have to clean and rebuild the project.

And here is our result after running the project on the emulator:

Good luck! ?

The article is available at:

Share the news now

Source : Viblo