Create Once. Use Everywhere, with Custom Views: Part 1

Create Once. Use Everywhere, with Custom Views: Part 1

Β·

0 min read

Recently I needed a simple counter for my app, since I had done it before it seemed logical to navigate to one of my projects with the implementation of this simple counter and copy-paste it into my codebase and make any necessary modifications from ids to positioning and everything else....well technically this is just too much overhead if I ever needed it somewhere else.

So on to my next logical decision, search for a similar implementation of what I want on an open-source host like Github. I actually would have stopped here but none of the available implementations fully met my requirements I needed it to be as simple as simple can be.

On to the next step which was to create my own simple version of the counter and serve it as a library that I can use if I or anyone else ever needed it againπŸ˜ƒ

Enough talk lets get into some action...πŸš€

Creating The Project

NB: I'll be using Android Studio 3.5 for this short demo. In the event, you are on a different version or using other IDEs like Intellij you can map similar functionalities.

To begin, you will first need to create a project like any other android app and assign it the name you wish to call your library in my case simple-counter.

Once that is done switch to the Project view like so

Switch to Project View.png

Next, we need to create a module that will contain our library code away from the normal app module we are accustomed to. Right-click on the project name to see the below menu.

Create Module.png

Android libraries usually come in two flavours;

  • Android Library
  • Java/Kotlin Library

Quick Recap

A View is simply a class that's responsible for items drawing onto the screen and taking up a rectangular area and is implemented to take various forms e.g ImageView, Button.

A Custom View builds upon implementations of views or the View class itself for a more customized experience. e.g MoviesImageView.

In our case since we are interested in creating a custom view, which is dependent on the View class that is available through the Android APIs, we will be creating an Android library.

Select module.png

And once done switch to the android view and you should have a structure similar to this.

Android View.png

Now we can start writing our custom view in the android library module,it has a similar structure to the app module.

Project on Github

In the next article, we will get into building the custom view. Part 2