Common libraries are essential in development. They are very useful and can avoid hours of unwanted development. In a previous article, I talked about how to create an android library project and why you should create one for your projects.
In this article, I will talk about how to import and use this library in your Android Application Project.
First, let's create a basic application.
Start Android Studio and choose
Start a new Android Studio project.
Now let's use as Application name:
HelloJar and the Company Domain:
Phone and Tablet and choose your API level (I use API 15).
You can customize the
Blank Activity settings if you want. For this demo, we will use the default values.
The main layout will (or should be) open and you will see the "Hello world!" text in the preview emulator.
Let's change this to display:
Hello Book of Zeus.
First we need to import the .JAR file by copying the library in the
libs folder. Make sure you are in the
Project view mode (Top left corver of the Project window).
Right click on the .JAR file and select the last option
Add as library.
Gradle should add the library automatically. But just in case open the build.gralde (Module: app) and look under
dependencies. You should see something like this:
Now that the library is added, clean the project (Build -> Clean Project). You should see
BUILD SUCCESSFUL in the gradle console.
To change the text of the TextView object, we will need to make sure the main class (in my case
MainActivity) access the TextView.
First, we will need to create an ID to the TextView:
<TextView android:id="@+id/txt_hello" android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" />
Let's modify the "Hello world!" to show,
Hello %s! instead!
strings.xml and update the
hello_world value to:
<string name="hello_world">Hello %s!</string>
Then, in the .java file let's use it.
TextView mHello = (TextView)findViewById(R.id.txt_hello);
Let's now use the library object. Remember the structure of the
LibraryDemo lib = new LibraryDemo(); CharSequence name = (CharSequence)lib.getSiteName();
And set the text to the TextView:
Make sure you import the
import com.mylibrary.LibraryDemo; before compiling the application.
Clean and run the project!
Download this project at https://github.com/bookofzeus/HelloJar