Improving Layout

The Android SDK includes tools to help us identify problems in our layout performance.

Optimizing Layout Hierarchies

  • Hierarchy Viewer

    It displays the layout tree. The traffic lights on each block represent its Measure, Layout and Draw performance. It is clear where we should spend time optimizing.

    Layout hierarchy

We can make the layout shallow and wide, rather than narrow and deep.

  • Use Lint

    Lint automatically runs whenever we compile our program.

Re-using Layouts

  1. Use the<include> Tag
  2. Use the<merge>Tag

Loading Views On Demand

We can reduce memory usage and speed up rendering by loading the views only when they are needed.

  • Define a ViewStub
  • Load the ViewStub Layout
    ((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
    // or 
    View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
    

    One drawback ofViewStubis that it doesn’t currently support the<merge/>tag in the layouts to be inflated.

Making ListView Scrolling Smooth

The key to a smoothly scrollingListViewis to keep the application’s main thread (the UI thread) free from heavy processing.

  • Use a Background Thread

    // Using an AsyncTask to load the slow images in a background thread
    new AsyncTask<ViewHolder, Void, Bitmap>() {
     private ViewHolder v;
    
     @Override
     protected Bitmap doInBackground(ViewHolder... params) {
         v = params[0];
         return mFakeImageLoader.getImage();
     }
    
     @Override
     protected void onPostExecute(Bitmap result) {
         super.onPostExecute(result);
         if (v.position == position) {
             // If this item hasn't been recycled already, hide the
             // progress and set and show the image
             v.progress.setVisibility(View.GONE);
             v.icon.setVisibility(View.VISIBLE);
             v.icon.setImageBitmap(result);
         }
     }
    }.execute(holder);
    

    Beginning with Android 3.0 (API level 11), we can useexecuteOnExecutor()and multiple requests can be executed at the same time depending on the number of cores available.

  • Hold View Objects in a View Holder

    Our code might callfindViewById()frequently during the scrolling ofListView, which can slow down performance.

results matching ""

    No results matching ""