How To Make an Android UI Part 2: Java code

After reading part one which discusses what Views and ViewGroups are, as well as how to create them in XML, the next step is to incorporate them into your Android application. How you use the UI you wrote depends on what it’s used for. Let’s break down some of the key things:

Activities

Activities are a specific focus for the user. Nearly every Activity you create will display a window for the user, which is defined using the setContentView() function. There are a few overloads for this method, the most popular being one that takes an integer resource to your xml file. That is why you will often see the following code in a default template:

This call to setContentView() is required in order to see anything displayed in the Activity, and it must also be called before any interaction with the UI elements in the Activity, which we’ll talk about later.  Next, let’s discuss how Fragments get their layouts.

Fragments

A fragment is just a part of your app’s UI that can be placed within an Activity. Fragments do not use the setContentView() method, but instead implement onCreateView() to initialize a Fragment’s User Interface. A LayoutInflater object is used to inflate the layout:

Again, we’ll come back to what kinds of actions you can preform on Views a little later. For now, let’s try to really understand what’s happening behind the scenes in a LayoutInflater.

LayoutInflater

The concept is rather simple, but important to understand what is going on. A LayoutInflater instantiates a layout XML file into its corresponding View objects. In other words, when you have your LinearLayout and children defined in XML, the inflater will create actually View objects for you that you can manipulate in code. This is your gateway into everything you will need to create a positive user experience.

Accessing Views

If you ever need to manipulate view, whether you’re setting text, reading input, or handling clicks programatically, you’ll need to create an object in your code. To access that object, you can use the View.findViewbyId() method. There also exists an Activity.findViewById() method, which means you can just call the method directly inside an Activity:

Once you’ve learned how to create your XML files, inflate the views, and access specific elements, you have the base foundation required to create beautiful interactive interfaces. Unfortunately, there are too many different things you can do for me to discuss them all here, so I highly encourage you to look at the docs to understand the various attributes of UI elements and learn the different ways to style them and manipulate them. I hope this gave you a better understand of the User Interface.

Share this post...
Share on Reddit0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Facebook0

Leave a Reply