Home > Articles > Mobile Application Development & Programming

How to Handle Common Android UI Components

A lot of different UI components are common to apps. Splash screens and loading indicators, for example, are very common but have several different implementations. There are times when you need to include complex styling for text or even inline images, but do not want to create several views. You may want to improve the user experience by loading content just before the user needs it. In this chapter, you will learn about these common app components and the best way to develop them.

Read Android User Interface Design: Turning Ideas and Sketches into Beautifully Designed Apps or more than 24,000 other books and videos on Safari Books Online. Start a free trial today.

This chapter is from the book

Splash Screen

Splash screens are typically still images that fill the screen of a mobile device. On a desktop computer, they can be full screen (such as for an operating system) or a portion of the screen (for example, Photoshop, Eclipse, and so on). They give feedback that the system has responded to the user’s action of opening the application. Splash screens can include loading indicators but are often static images.

Do You Really Need It?

Looking back at the previous examples (operating systems, Photoshop, and Eclipse), you should notice something in common with desktop uses of splash screens: The applications are large. They need to show the user something while they are loading so that the user will not feel like the computer has locked up or failed to respond to the user’s actions.

Compared to massive applications such as Photoshop, your Android app is very small and likely loading from flash storage rather than a slower, spinning disk. Many people also have the mistaken conception that because iOS apps require splash screens that Android apps do, too. Related, when an app already exists on iOS and is being built for Android afterward, many people think that it should have a splash screen in both places to be consistent, but you should play to the strengths of each platform and take advantage of how fast Android apps load. So, does your app really need a splash screen?

The correct answer to start with is no, until you have proven it a necessity. Splash screens are often abused as a way of getting branding in front of the user, but they should only be used if loading is going on in the background. An app that artificially displays a splash screen for a few seconds is preventing the user from actually using the app, and that is the whole reason the user has the app in the first place. Mobile apps are especially designed for quick, short uses. You might have someone pushing for more heavy-handed branding, but that can ultimately hurt the app and the brand itself if users find they have two wait a few extra seconds when they open the app but they don’t have to wait with a competitor’s app.

That said, there are genuine times when a splash screen is needed. If you cannot show any UI until some loading takes place that could take a while, then it makes sense to show a splash screen. A good example of this is a game running in OpenGL that needs to load several textures into memory, not to mention sound files and other resources. Another example is an app that has to load data from the Web. For the first run, the app might not have any content to display, so it can show a splash screen while the web request is made, making sure to give an indication of progress. For subsequent loads, the cached data can be displayed while the request is made. If that cached data takes any significant amount of time, you might opt to show the splash screen there too until the cached content has loaded, then have a smaller loading indicator that shows the web request is still in progress. If you want to display a splash screen because your layout takes a long time to display, you should first consider making your layout more efficient.

Keep in mind that the user might want to take an action immediately and does not care about the main content. You would not want the Google Play app to show a splash screen for five seconds because it is loading the top content when you are actually just opening it to search for a specific app.

Ultimately, you should opt to skip on the splash screen unless you have developed the app and it is absolutely necessary. When in doubt, it is not needed.

Using a Fragment for a Splash Screen

If you have determined that your app is one of the few that does truly require a splash screen, one approach for displaying it is to use a Fragment. You immediately show it in your onCreate(Bundle) method, start your loading on a background thread, and replace the Fragment with your actual UI Fragment when your loading has completed. That sounds easy enough, but what does it really look like?

First, create the Fragment that you will use for the splash screen. You’ll probably have some kind of branded background, but this example will just use a simple XML-defined gradient for the background (see Listing 10.1).

Listing 10.1. A Simple Gradient Saved as splash_screen_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

        android:startColor="@android:color/black" />


Next, create a layout for the splash screen. This example will use a really simple layout that just shows the text “Loading” and a ProgressBar. Notice that the style is specifically set on the ProgressBar to make this a horizontal indicator (instead of an indeterminate indicator) in Listing 10.2.

Listing 10.2. The Splash Screen Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" >

        android:textAppearance="@android:style/TextAppearance.Medium.Inverse" />

        android:max="100" />


The last piece of the splash screen portion is to create a simple Fragment that displays that layout. The one requirement of this Fragment is that it has a way of updating the ProgressBar. In this example, a simple setProgress(int) method is tied directly to the ProgressBar in the layout. See Listing 10.3 for the full class and Figure 10.1 for what this will look like in use.

Figure 10.1

Figure 10.1. The simple splash screen with loading indicator

Listing 10.3. The Fragment That Displays the Splash Screen

public class SplashScreenFragment extends Fragment {

    private ProgressBar mProgressBar;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.splash_screen, container, false);
        mProgressBar = (ProgressBar) view.findViewById (R.id.progress_bar);
        return view;

     * Sets the progress of the ProgressBar
     * @param progress int the new progress between 0 and 100
    public void setProgress(int progress) {

Now that the easy part is done, you need to handle loading the data. Prior to the introduction of the Fragment class, you would do this with a simple AsyncTask in your Activity that you would save and restore during config changes (attaching and detaching the Activity to avoid leaking the Context). This is actually easier now with a Fragment. All you have to do is create a Fragment that lives outside of the Activity lifecycle and handles the loading. The Fragment does not have any UI because its sole purpose is to manage loading the data.

Take a look at Listing 10.4 for a sample Fragment that loads data. First, it defines a public interface that can be used by other classes to be notified of progress with loading the data. When the Fragment is attached, it calls setRetainInstance(true) so that the Fragment is kept across configuration changes. When the user rotates the device, slides out a keyboard, or otherwise affects the device’s configuration, the Activity will be re-created but this Fragment will continue to exist. It has simple methods to check if loading is complete and to get the result of loading the data (which is stored as a Double for this example, but it could be anything for your case). It can also set and remove the ProgressListener that is notified of updates to the loading.

The Fragment contains an AsyncTask that does all the hard work. In this case, the background method is combining some arbitrary square roots (to mimic real work) and causing the Thread to sleep for 50ms per iteration to create a delay similar to what you might see with real use. This is where you would grab assets from the Web, load them from the disk, parse a complex data structure, or do whatever you needed to finish before the app is ready.

On completion, the AsyncTask stores the result, removes its own reference, and notifies the ProgressListener (if one is available).

Listing 10.4. A Fragment That Handles Loading Data Asynchronously

public class DataLoaderFragment extends Fragment {

     * Classes wishing to be notified of loading progress/completion
     * implement this.
    public interface ProgressListener {
         * Notifies that the task has completed
         * @param result Double result of the task
        public void onCompletion(Double result);

         * Notifies of progress
         * @param value int value from 0-100
        public void onProgressUpdate(int value);

    private ProgressListener mProgressListener;
    private Double mResult = Double.NaN;
    private LoadingTask mTask;

    public void onAttach(Activity activity) {

        // Keep this Fragment around even during config changes

     * Returns the result or {@value Double#NaN}
     * @return the result or {@value Double#NaN}
    public Double getResult() {
        return mResult;

     * Returns true if a result has already been calculated
     * @return true if a result has already been calculated
     * @see #getResult()
    public boolean hasResult() {
        return !Double.isNaN(mResult);

     * Removes the ProgressListener
     * @see #setProgressListener(ProgressListener)
    public void removeProgressListener() {
        mProgressListener = null;

     * Sets the ProgressListener to be notified of updates
     * @param listener ProgressListener to notify
     * @see #removeProgressListener()
    public void setProgressListener(ProgressListener listener) {
        mProgressListener = listener;

     * Starts loading the data
    public void startLoading() {
        mTask = new LoadingTask();

    private class LoadingTask extends AsyncTask<Void, Integer, Double> 

        protected Double doInBackground(Void... params) {
            double result = 0;
            for (int i = 0; i < 100; i++) {
                try {
                    result += Math.sqrt(i);
                } catch (InterruptedException e) {
                    return null;
            return Double.valueOf(result);

        protected void onPostExecute(Double result) {
            mResult = result;
            mTask = null;
            if (mProgressListener != null) {

        protected void onProgressUpdate(Integer... values) {
            if (mProgressListener != null) {

To tie everything together, you need an Activity. Listing 10.5 shows an example of such an Activity. It implements the ProgressListener from the DataLoaderFragment. When the data is done loading, the Activity simply displays a TextView with the result (that’s where you would show your actual app with the necessary data loaded in). When notified of updates to loading progress, the Activity passes those on to the SplashScreenFragment to update the ProgressBar.

In onCreate(Bundle), the Activity checks whether or not the DataLoaderFragment exists by using a defined tag. If this is the first run, it won’t exist, so the DataLoaderFragment is instantiated, the ProgressListener is set to the Activity, the DataLoaderFragment starts loading, and the FragmentManager commits a FragmentTransaction to add the DataLoaderFragment (so it can be recovered later). If the user has rotated the device, the DataLoaderFragment will be found, so the app has to check whether or not the data has already loaded. If it has, the method is done; otherwise, everything falls through to checking if the SplashScreenFragment has been instantiated, creating it if it hasn’t.

The onStop() method removes the Activity from the DataLoaderFragment so that your Fragment does not retain a Context reference and the app avoids handling the data result if it’s not in the foreground. Similarly, onStart() checks if the data has been successfully loaded.

The last method, checkCompletionStatus(), checks if the data has been loaded. If it has, it will trigger onCompletion(Double) and remove the reference to the DataLoaderFragment. By removing the reference, the Activity is able to ensure that the result is only handled once (which is why onStart() checks if there is a reference to the DataLoaderFragment before handling the result). Figure 10.2 shows what the app looks like once it has finished loading the data.

Figure 10.2

Figure 10.2. The resulting app after data has loaded

Listing 10.5. The Activity That Ties Everything Together

public class MainActivity extends Activity implements ProgressListener {

    private static final String TAG_DATA_LOADER = "dataLoader";
    private static final String TAG_SPLASH_SCREEN = "splashScreen";

    private DataLoaderFragment mDataLoaderFragment;
    private SplashScreenFragment mSplashScreenFragment;

    public void onCompletion(Double result) {
        // For the sake of brevity, we just show a TextView with the result
        TextView tv = new TextView(this);
        mDataLoaderFragment = null;

    public void onProgressUpdate(int progress) {

    protected void onCreate(Bundle savedInstanceState) {

        final FragmentManager fm = getFragmentManager();
        mDataLoaderFragment = (DataLoaderFragment) fm.findFragmentByTag(TAG_DATA_LOADER);
        if (mDataLoaderFragment == null) {
            mDataLoaderFragment = new DataLoaderFragment();
            fm.beginTransaction().add(mDataLoaderFragment, TAG_DATA_LOADER).commit();
        } else {
            if (checkCompletionStatus()) {

        // Show loading fragment
        mSplashScreenFragment = (SplashScreenFragment) fm.findFragmentByTag(TAG_SPLASH_SCREEN);
        if (mSplashScreenFragment == null) {
            mSplashScreenFragment = new SplashScreenFragment();
            fm.beginTransaction().add(android.R.id.content, ]mSplashScreenFragment, TAG_SPLASH_SCREEN).commit();

    protected void onStart() {
        if (mDataLoaderFragment != null) {

    protected void onStop() {
        if (mDataLoaderFragment != null) {

     * Checks if data is done loading, if it is, the result is handled
     * @return true if data is done loading
    private boolean checkCompletionStatus() {
        if (mDataLoaderFragment.hasResult()) {
            FragmentManager fm = getFragmentManager();
            mSplashScreenFragment = (SplashScreenFragment) fm.findFragmentByTag(TAG_SPLASH_SCREEN);
            if (mSplashScreenFragment != null) {
                fm.beginTransaction().remove(mSplashScreenFragment). commit();
            return true;
        return false;

Quite a bit is going on in this small bit of code, so it’s a good idea to review it. On a high level, you are using DataLoaderFragment to load all the data, and it exists outside of configuration changes. The Activity checks DataLoaderFragment each time it is created and started to handle the result. If it’s not done yet, the SplashScreenFragment is shown to indicate progress.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020