UI Trick: Sliding content

Here is a small trick that I use sometimes to show a related content in an activity. In the back of my mind, my intention might be to mimic the iphone's presentModalViewController. This would specifically be useful when you have a list of items which users might repeatedly click items to view an Expanded view of them. I prefer to use this instead of a new Activity.
The basic idea is simple: Use a SlidingDrawer with an invisible handle.

In your activity add the SlidingDrawer to your content view. I usually set the Handle's height and width to 0dp. Then when you want to show the Expanded View you can just open the drawer.

To hide or show the drawer is pretty straight forward using animateOpen and animateClose of the SlidingDrawer. It is preferable to wrap these calls in your own functions in order to be able to add your own code upon closing/opening the drawer. I know that we can use the  OnDrawerOpenListener and OnDrawerCloseListener: just a matter of taste. Just wrap them in your own calls:


public void showDrawer() {
 mDrawer.animateOpen();
}
public void hideDrawer() {
 mDrawer.animateClose();
}


An important point to keep in mind is to handle the onBackPressed() of the activity that contains such a drawer

@Override
public void onBackPressed() {
 if(mDrawer.isOpened())
  hideDrawer();
 else
  super.onBackPressed();
}


Click here for Sample Project + Source Code (download)

Here is the full code of the activity.

public class MainActivity extends Activity {
 SlidingDrawer mDrawer;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDrawer = (SlidingDrawer) findViewById(R.id.drawer);
        findViewById(R.id.buttonshow).setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    showDrawer();
   }
        });
        findViewById(R.id.buttonhide).setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    hideDrawer();
   }
        });
    }

    public void showDrawer() {
     mDrawer.animateOpen();
    }
    public void hideDrawer() {
     mDrawer.animateClose();
    }
    
    @Override
    public void onBackPressed() {
     if(mDrawer.isOpened())
      hideDrawer();
     else
      super.onBackPressed();
    }
    
}

3 comments:

  1. You might have a look on a library I'm working to get expandable views in Android: https://github.com/AndreasZeiser/Jalousie

    ReplyDelete
    Replies
    1. I will check it out. Downloading library and sample.

      Delete
    2. I have posted a comment in the issue tracker.

      Delete