Home > Articles > Programming

How to Handle Common Android UI Components

  • Print
  • + Share This
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" >

    <gradient
        android:angle="90"
        android:centerColor="#FF223333"
        android:endColor="@android:color/black"
        android:startColor="@android:color/black" />

</shape>

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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splash_screen_bg"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/loading"
        android:textAppearance="@android:style/TextAppearance.Medium.Inverse" />

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:max="100" />

</LinearLayout>

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;

    @Override
    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) {
        mProgressBar.setProgress(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;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // Keep this Fragment around even during config changes
        setRetainInstance(true);
    }

    /**
     * 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();
        mTask.execute();
    }

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

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

        @Override
        protected void onPostExecute(Double result) {
            mResult = result;
            mTask = null;
            if (mProgressListener != null) {
                mProgressListener.onCompletion(mResult);
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (mProgressListener != null) {
                mProgressListener.onProgressUpdate(values[0]);
            }
        }
    }
}

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;

    @Override
    public void onCompletion(Double result) {
        // For the sake of brevity, we just show a TextView with the result
        TextView tv = new TextView(this);
        tv.setText(String.valueOf(result));
        setContentView(tv);
        mDataLoaderFragment = null;
    }

    @Override
    public void onProgressUpdate(int progress) {
        mSplashScreenFragment.setProgress(progress);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

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

        // 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();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mDataLoaderFragment != null) {
            checkCompletionStatus();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mDataLoaderFragment != null) {
            mDataLoaderFragment.removeProgressListener();
        }
    }

    /**
     * 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()) {
            onCompletion(mDataLoaderFragment.getResult());
            FragmentManager fm = getFragmentManager();
            mSplashScreenFragment = (SplashScreenFragment) fm.findFragmentByTag(TAG_SPLASH_SCREEN);
            if (mSplashScreenFragment != null) {
                fm.beginTransaction().remove(mSplashScreenFragment). commit();
            }
            return true;
        }
        mDataLoaderFragment.setProgressListener(this);
        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.

  • + Share This
  • 🔖 Save To Your Account