Creating a View Class

It comes without saying that Android is a unique mobile operating system with flexible platform which allows developers to realize their goals. Sometimes what users want is beyond imagination and the developer couldn’t implement it by simple UI components or it might be some parts of code  that can be used in more than one layout files.

One of the possible solutions to this kind of problem can be the following:

Create separate layout file with common structure and include it in other layout file. The action solves the problem partially, because in many cases you should inflate layouts and make the same standard calls such as  findViewById() , setText(), setBackground() and etc.

Therefore, it would be perfect to have one common method, which will give an opportunity to initialize more fields.

It’s a common knowledge that Android provides solution to create our custom UI elements.

Here is an example where we have an object that has a name , image and the function whether it is checked or not.

custom_view.xml

Let’s create our custom view object:

As it is shown we have setData function which initialize all the fields in our view object immediately.

Hence,we created the UI element class that can initialize several fields with one function at the same time. As it is an UI element, it should  also be used in layout files. There comes an issue how to initialize the fields in our UI object.

And now we reached to the most important part.

Firstly, we need to create attrs.xml file@ ..res/values in the folder and declare the attributes there.

By this action, our custom UI object gets specific attributes.

Once you define the custom attributes, you can use them in layout XML files just like built-in attributes. The only difference is that your custom attributes belong to a different namespace. Instead of belonging to the http://schemas.android.com/apk/res/android namespace, they belong to http://schemas.android.com/apk/res/[your package name].

For example, here’s how to use the attributes defined for CustomView:

Here we use layout_width  and layout_height attributes, which are  standard and required for each view object. But the itemImage and itemText  are specific for CostomView object. It can’t be used for any other Android standart view object, even if it’s in they are at the  same layout.

  • Topics:
  • Android

Top Stories

High Five! You just read 2 awesome articles, in row. You may want to subscribe to our blog newsletter for new blog posts.