How to Create Your Own Android Library in Android Studio

In this tutorial, we will learn how to create our own android library in android studio.

If you have been programming for something now on android platform, there is a big chance you have used someone’s library in your project.

Have you ever wondered how these libraries are created by other developers? At the end of this tutorial you will be ready to create that android library you have always had in mind.

Android library is created most often when you have a code you will like to share between multiple projects. It does not only saves development time it also offer secured and tested code.

Beside that, when developers and companies find a solution to a problem that will be beneficial to android developers’ community the best way to share their source code is to bundle it in a library and open source it.

This is a two part tutorial. In this first part we will focus on how to build android libraries for developers and in part two, we will focus more on how to publish our android library on Bintray and jCenter.

What solution will our android library provides?

We are going to create a simple color picker android library. I know there are lots of android color picker library out there. Creating this android library is basically for learning purpose.

Below are some of the screenshots for the library.

how to build android library

Create Android Library Module

Creating android application in android studio is similar to creating a library module. We are going to follow the steps below to create our android library module

Click on File > New > New Module as shown below.

android library module

Click on the highlighted New Module link to open the module dialog as show below.

android library for developer

Click on the Android Library button as show above to enter your library name and the targeted android SDK. I have chosen ColorPicker but feel free to choose any name of your choice.

Finally, click on the activated finish button and wait for a few second for Android Studio to add the library module.

If everything works well for you then lets spend sometime to think about how to design and structure our android library.

Designing Android Library

Just like in application development, it is always a bad idea to just jump into your IDE and start coding. So we will briefly explore what to think about and decided on before we start developing our android library.

Even though we will not use most of them but it is important to know them

  1. Library API documentation – since we are not build our library just for ourselves, it is important to have a well documented, detailed and easy to understand guide for other developers.
  2. We need to know methods to be expose and hidden
  3. There should be exception handler and validation to prevent the library from behaving the way it was not anticipated to behave.

For our android library, we are going to create a custom view which will contain other individual view widgets.

These include SeekBars, Buttons and TextViews. Beside the Custom compound view, we will also create an interface class with a single method that has a color int as parameter.

Finally we will create another Java class file that will contain color conversion methods. The methods will take in values from SeekBar widgets and convert the values to a color code.

Create a Java Class file name ColorPicker.java

Right click on the src directory of your library project and select New > New Java Class.

Enter the name of the class as ColorPicker and click finish to create the file.

Open the created ColorPicker class and paste the code below in the class.

public class ColorPicker implements SeekBar.OnSeekBarChangeListener{

    private static final String TAG = ColorPicker.class.getSimpleName();

    private Context context;

    private AlertDialog alertDialog;


    private LinearLayoutCompat colorPreview;

    AppCompatTextView redBarCount, greenBarCount, blueBarCount;

    AppCompatButton okButton, cancelButton;

    private int redValue, greenValue, blueValue = 0;

    AppCompatSeekBar redSeekBar, greenSeekBar, blueSeekBar;

    public OnColorSelectChangeListener onColorSelectChangeListener;

    private ColorConverter colorConverter;

    private int currentColor;


    public ColorPicker(Context context) {
        this.context = context;
        colorConverter = new ColorConverter(context);
        currentColor = R.color.colorBackground;
        initColorPicker();
    }


    public void initColorPicker(){
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.color_picker_layout, null);
        builder.setView(view);

        colorPreview = (LinearLayoutCompat) view.findViewById(R.id.color_preview);

        redBarCount = (AppCompatTextView)view.findViewById(R.id.red_bar_count);
        greenBarCount = (AppCompatTextView)view.findViewById(R.id.green_bar_count);
        blueBarCount = (AppCompatTextView)view.findViewById(R.id.blue_bar_count);

        redSeekBar = (AppCompatSeekBar)view.findViewById(R.id.color_bar_red);
        greenSeekBar = (AppCompatSeekBar)view.findViewById(R.id.color_bar_green);
        blueSeekBar = (AppCompatSeekBar)view.findViewById(R.id.color_bar_blue);

        redSeekBar.setOnSeekBarChangeListener(this);
        greenSeekBar.setOnSeekBarChangeListener(this);
        blueSeekBar.setOnSeekBarChangeListener(this);

        builder.setCancelable(false);
        alertDialog = builder.create();

        okButton = (AppCompatButton) view.findViewById(R.id.ok_button);
        okButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onColorSelectChangeListener.onColorChange(currentColor);
                alertDialog.dismiss();
            }
        });


        cancelButton = (AppCompatButton)view.findViewById(R.id.cancel_button);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }


    public void show(){
        alertDialog.show();
    }


    public void hide(){
        alertDialog.hide();
    }


    public void setDefaultColor(int backgroundColor){
        colorPreview.setBackgroundColor(backgroundColor);
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Log.d(TAG, "Log progress " + progress);
        int id = ((SeekBar)seekBar).getId();
        if(id == R.id.color_bar_red){
            redValue = progress;
        }
        if(id == R.id.color_bar_green){
            greenValue = progress;
        }
        if(id == R.id.color_bar_blue){
            blueValue = progress;
        }
        currentColor = colorConverter.convertIntValuesToColor(redValue, greenValue, blueValue);
        Log.d(TAG, "Log current color " + progress);
        setDefaultColor(currentColor);
    }


    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }


    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }


    public void setOnColorSelectChangeListener(OnColorSelectChangeListener onColorSelectChangeListener){
        this.onColorSelectChangeListener = onColorSelectChangeListener;
    }

}

You can see from the above code that we have created an android dialog class that inflates a layout. The layout contains the view widgets we will use to select each individual RGB color channel.

We will create a new layout file for our view widgets

1. Go to your project res folder > layout folder and right click. Select New > Layout resource then add the name of your resource layout as color_picker_layout.xml.

Open the color_picker_layoutfile and paste the code below in the file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorDark"
    android:layout_marginEnd="40dp"
    android:layout_marginTop="10dp"
    android:layout_marginStart="40dp">


    <androidx.appcompat.widget.LinearLayoutCompat
        android:id="@+id/color_preview"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@color/colorBackground"
        android:orientation="vertical">

    </androidx.appcompat.widget.LinearLayoutCompat>


    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:background="@color/colorDark"
        android:padding="12dp"
        android:orientation="vertical">

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="4dp"
            android:paddingBottom="4dp"
            android:orientation="horizontal">

            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="R"
                android:textColor="@color/colorWhite"
                android:textSize="13sp"
                android:layout_weight="1"/>

            <androidx.appcompat.widget.AppCompatSeekBar
                android:id="@+id/color_bar_red"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:max="255"
                android:progress="0"
                android:layout_weight="5"/>

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/red_bar_count"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="255"
                android:gravity="right"
                android:textColor="@color/colorWhite"
                android:textSize="13sp"
                android:layout_weight="1"/>

        </androidx.appcompat.widget.LinearLayoutCompat>

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:paddingTop="4dp"
            android:paddingBottom="4dp"
            android:orientation="horizontal">

            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="G"
                android:textColor="@color/colorWhite"
                android:textSize="13sp"
                android:layout_weight="1"/>

            <androidx.appcompat.widget.AppCompatSeekBar
                android:id="@+id/color_bar_green"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:max="255"
                android:progress="0"
                android:layout_weight="5"/>

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/green_bar_count"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="255"
                android:gravity="right"
                android:textColor="@color/colorWhite"
                android:textSize="13sp"
                android:layout_weight="1"/>

        </androidx.appcompat.widget.LinearLayoutCompat>

        <androidx.appcompat.widget.LinearLayoutCompat
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="4dp"
            android:paddingBottom="4dp"
            android:layout_marginTop="20dp"
            android:orientation="horizontal">

            <androidx.appcompat.widget.AppCompatTextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="B"
                android:textColor="@color/colorWhite"
                android:textSize="13sp"
                android:layout_weight="1"/>

            <androidx.appcompat.widget.AppCompatSeekBar
                android:id="@+id/color_bar_blue"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:max="255"
                android:progress="0"
                android:layout_weight="5"/>

            <androidx.appcompat.widget.AppCompatTextView
                android:id="@+id/blue_bar_count"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:text="255"
                android:gravity="right"
                android:textColor="@color/colorWhite"
                android:textSize="13sp"
                android:layout_weight="1"/>

        </androidx.appcompat.widget.LinearLayoutCompat>

    </androidx.appcompat.widget.LinearLayoutCompat>


    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorDark"
        android:padding="12dp"
        android:gravity="right"
        android:orientation="horizontal">

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/cancel_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorWhite"
            android:text="CANCEL"
            android:background="@android:color/transparent"/>

        <androidx.appcompat.widget.AppCompatButton
            android:id="@+id/ok_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/colorWhite"
            android:text="OK"
            android:background="@android:color/transparent"/>

    </androidx.appcompat.widget.LinearLayoutCompat>

</androidx.appcompat.widget.LinearLayoutCompat>

There are some missing color resources in the layout file above

2. Let go back to the res folder, inside the res folder there is a values folder there. Right click on the values folder and select New > resource file.

Enter colors in the dialog and click enter to create a new colors resource file inside the values folder.

Open the colors.xmlfile and paste the code below inside the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorDark">#444444</color>
    <color name="colorWhite">#ffffff</color>
    <color name="colorBackground">#908282</color>
</resources>

3. Create the ColorConverterjava class like we did when we created the initial java class. Open the class and paste the code below inside the class.

import android.content.Context;
import android.graphics.Color;

public class ColorConverter {

    private static final String TAG = ColorConverter.class.getSimpleName();

    private Context context;


    public ColorConverter(Context context) {
        this.context = context;
    }


    public int convertIntValuesToColor(int redColor, int greenColor, int blueColor){
        return Color.rgb(redColor, greenColor, blueColor);
    }


    public String ConvertColorToHexCode(int redColor, int greenColor, int blueColor ){
        int colorMix = Color.rgb(redColor, greenColor, blueColor);
        return String.format("#%06X", (0xFFFFFF & colorMix));
    }

}

Since our dialog layout file has an OK button, when a user selects a color and click the Ok button, we will expose the value of this color so that developers who will use our android library can get access to this resource data.

We will use an iterfaceclass with a single method that takes the color resource as parameter. Any class that wants access to the color data will implement this interface.

Create a new iterface classand name it OnColorSelectChangeListener

Add the below code in the interface class.

public interface OnColorSelectChangeListener {

    void onColorChange(int color);
}

Finally we are done with creating our own android library in android studio.

Next thing is to test our android library by adding it to a project and see if it works the way we expected it.

 Testing and Using the library

Using the default android project we created at the beginning, we will test our android library by using a button widget to trigger the library dialog.

When the ok button of the dialog is click the color resource value will be set to a textview widget.

1. Open the activity_main.xmland add the view widget code.

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/open_color_picker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="12dp"
        android:text="@string/open_color_picker"
        android:background="@color/colorAccent"/>


    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/selected_color"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Change Text Color" />

</androidx.appcompat.widget.LinearLayoutCompat>

2. In the MainActivityclass, we will get the instances of the view widgets.

Wire an event listener to the Button view so that when it is clicked, the color dialog will show.

The MainActivity class will implement OnColorSelectChangeListener interface and override the onColorChange()method. The TextView text color change happens inside this override method.

The complete code for the MainActivity class is shown below.

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.inducesmile.colorpickers.ColorPicker;
import com.inducesmile.colorpickers.OnColorSelectChangeListener;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;

public class MainActivity extends AppCompatActivity implements OnColorSelectChangeListener {


    private static final String TAG = MainActivity.class.getSimpleName();

    private AppCompatTextView showColorCode;

    private ColorPicker colorPicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        colorPicker = new ColorPicker(MainActivity.this);
        colorPicker.setOnColorSelectChangeListener(this);


        showColorCode = (AppCompatTextView)findViewById(R.id.selected_color);

        Button showColorPickerBtn = (AppCompatButton)findViewById(R.id.open_color_picker);
        showColorPickerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                colorPicker.show();
            }
        });
    }

    @Override
    public void onColorChange(int color) {
        Log.d(TAG, "Selected color " + color);
        showColorCode.setTextColor(color);
    }
}

For android project to recognize and use classes and methods from our android library, we need to add it as a dependency in the android project build.gradle.

Open android project build.gradle file and add this line in the dependencies section.

compile project(path: ':colorpickers')

Run your android application and start testing your library. If you have any error or question kindly use the comment box below.

Now that we have finish building our android library in android studio, the next tutorial will focus on how to publish our android library on Bintary and jCenter so that it will be available to developer just with one line of gradle code.

 

Add a Comment