SlidingDrawer in Android with Example

18 Feb, 2021
SlidingDrawer is a common requirement in android mobiles to view the content whenever needed by sliding horizontally as well as vertically. In this article, let us check out on Sliding Drawer which is used to hide the content out of the screen and allows the user to drag a handle to bring the content on the screen whenever needed in a very user-friendly way. Sliding drawer is a special widget and it contains two children’s views, one to handle that the user’s drags and the other is content attached to the handle which dragged along-with it. 
As this is the sliding drawer, we can drag and see the contents whenever necessary. So basically, open and close are the very important methods associated with that. In our example, by using that let us have a small demo code. Besides that other important methods also there and they are also discussed here. To initialize(or instantiate) a variable of SlidingDrawer, we need to do like below
Java
// First initiate the SlidingDrawer, simpleSlidingDrawer1 // is the id of SlidingDrawer defined in activity_main.xml// Here using simpleSlidingDrawer1 as object and // this is used throughout nextSlidingDrawer simpleSlidingDrawer1 = (SlidingDrawer) findViewById (R.id.simpleSlidingDrawer1);
Methods
Description
This method is similar to the open() method but with animation. 
We can also use this method on click of a View (Button or any other view)
This method is similar to the close() method but with animation. 
We can also use this method on click of a View (Button or any other view)
In many places, we may need to check whether the drawer is open or not. 
Resultant is a boolean value and if true, the drawer is opened
If there is a necessity to disable the touch events, we can use this method. 
Though it is a rare scenario, this facility is also available and 
it is used to lock the SliderDrawer and ignores the touch events. 
We can also use this method on click of a View (Button or any other view)
If accidentally locked i.e. touch events are disabled, it has to be unlocked. 
For that, we can use this method. We can also use this method on click of a View (Button or any other view)
Java
// important methods are discussed here  // open the Sliding DrawersimpleSlidingDrawer1.open();   // close the Sliding DrawersimpleSlidingDrawer1.close();   // open the Sliding Drawer but with an animationsimpleSlidingDrawer1.animateOpen();   // close the Sliding Drawer but with an animationsimpleSlidingDrawer1.animateClose();
Programmatically we may need to check whether the SlidingDrawer is opened or closed. For that, we can use the below set of methods.
Java
// check whether the slider is opened or not and // depends upon that we can do rest of the calculationsBoolean isSliderSrawerOpen = simpleSlidingDrawer1.isOpened();   // If we do not want touch events to occur, set thissimpleSlidingDrawer1.lock();   // In order to process the touch events// if accidentally locked or due to some requirement got lockedsimpleSlidingDrawer1. unlock();
Setter Methods:
setOnDrawerCloseListener(OnDrawerCloseListeneronDrawerCloseListener):  
This method is used to sets the listener that receives the notification when the drawer becomes close. The name of the method is self-explanatory. 
Java
simpleSlidingDrawer1.setOnDrawerCloseListener(    new SlidingDrawer.OnDrawerCloseListener() {        @Override public void onDrawerClosed()        {            // Suppose you can give a toast message or when            // drawer closes need to navigate to another            // event etc., So required steps are done here        }    });
setOnDrawerOpenListener(OnDrawerOpenListeneronDrawerOpenListener): 
This method is used to set the listener that receives the notification when the drawer becomes open. The name of the method is self-explanatory.
Java
simpleSlidingDrawer1.setOnDrawerOpenListener(    new SlidingDrawer.OnDrawerOpenListener() {        @Override public void onDrawerOpened()        {            // As per your requirement, add code here.        }    });
setOnDrawerScrollListener(OnDrawerScrollListeneronDrawerScrollListener): 
This method is used to set the listener that receives the notification when the drawer starts or ends a scroll. The name of the method is self-explanatory.
Java
simpleSlidingDrawer1.setOnDrawerScrollListener(    new SlidingDrawer.OnDrawerScrollListener() {        @Override public void onScrollStarted()        {            // Scroll is necessary for large data to view,            // so necessary code is required here        }          @Override public void onScrollEnded()        {            // add code here for the scroll ended.        }    });
In order to identify a SliderDrawer, certain attributes are very mandatory. 
Attributes
The id attribute is used to uniquely identify a SliderDrawer. In your entire code, with this id, 
SliderDrawer is accessed. This is the key field and by keeping meaningful and 
user-friendly names for id, future developers can easily understand and maintain the code
This attribute is used as an Identifier for the child that represents the drawer’s handle. 
This is always visible in the application
Here you can define the drawer’s content. In order to make the contents visible,
 one can click the handle and see it. open() and close() methods
are there to make content visible and invisible.
The default orientation is vertical. Sometimes there may be a requirement to make 
the orientation to be horizontal. This attribute makes the facility for it.
Let us see the whole example code for the provided video content. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
This usually comes under the res > layout folder. There may be necessities to have different layouts for different mobile sizes. But generally preferred is the layout folder. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout     xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/layout"    android:layout_width="fill_parent"    android:layout_height="fill_parent">      <SlidingDrawer        android:id="@+id/simpleSlidingDrawer1"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:content="@+id/content1"        android:handle="@+id/handle1"        android:orientation="horizontal"        android:rotation="180">          <!-- Let us define the button -->        <Button            android:id="@id/handle1"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:background="#0f0"            android:rotation="270"            android:text="Open"            android:textColor="#fff" />          <!-- layout for the content of the SlidingDrawer -->        <LinearLayout            android:id="@id/content1"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:orientation="horizontal"            android:rotation="180">              <!-- DEFINE ALL YOUR CONTENT,WIDGETS HERE                  WHICH YOU WANT TO ADD IN SLIDING DRAWER LAYOUT. -->            <ListView                android:id="@+id/simpleListView1"                android:layout_width="fill_parent"                android:layout_height="fill_parent" />                      </LinearLayout>    </SlidingDrawer></LinearLayout>
Step 3: Create a new layout resource file
Go to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as list_item.xml. This XML is going to hold the contents which you are specifying in the ArrayAdapter. Let us declare them in LinearLayout with a vertical orientation so that contents can be scrolled up and down in a vertical direction.
XML
<?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="wrap_content"    android:orientation="vertical">          <!-- TextView for the list item -->    <TextView        android:id="@+id/name1"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:padding="10dp"        android:textColor="#0f0" /></LinearLayout>
Step 4: Working with the MainActivity.java file
Now go to the java folder and in MainActivity.java and provide the implementation to the SlidingDrawer. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.ListView;import android.widget.SlidingDrawer;import androidx.appcompat.app.AppCompatActivity;  public class MainActivity extends AppCompatActivity {      String[] nameArray = {"Bitcoin", "Ethereum", "Litecoin", "IOTA", "Libra", "Monero", "EOS",                          "NEO", "ATOM", "Tether", "XRP", "Bitcoin Cash", "Binance Coin", "REN",                          "Bitcoin SV", "USD Coin", "Stellar", "Tezos", "Dash", "Zcash"};      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);          // initiate the SlidingDrawer        SlidingDrawer simpleSlidingDrawer1 = (SlidingDrawer) findViewById(R.id.simpleSlidingDrawer1);          // initiate a Button which is used for         // handling the content of SlidingDrawer        // We can able to have open and close         // methods for this handleButton        final Button handleButton = (Button) findViewById(R.id.handle1);          // initiate the ListView that is used for content of Sl.idingDrawer        // adapter for the list view. As all are text,         // it is defined as ArrayAdapter<String>        // Your cryptocurrency items are going to be displayed via this        // view using below cryptocurrency ArrayAdapter        ListView simpleListView1 = (ListView) findViewById(R.id.simpleListView1);          // Below syntax is for defining ArrayAdapter        ArrayAdapter<String> cryptocurrencyArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),                R.layout.list_item, R.id.name1, nameArray);          // set an adapter to fill the data in the ListView        simpleListView1.setAdapter(cryptocurrencyArrayAdapter);          // implement setOnDrawerOpenListener event,        // name itself suggests that        // we need to write code for drawer opening        simpleSlidingDrawer1.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {            @Override            public void onDrawerOpened() {                // When drawer is opened, we may need                 // to indicate user that close option                // is available, so just setting text to close.                 // But required functionality can be done here                handleButton.setText("Close");            }        });          // implement setOnDrawerCloseListener event,        // name itself suggests we need to write close events        simpleSlidingDrawer1.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {            @Override            public void onDrawerClosed() {                // if close is done, we should have the option to open.                // according to the requirement,                 // carry out necessary steps for close                handleButton.setText("Open");            }        });    }}
On setting the code in Android studio, we can able to see the SlidingDrawer working correctly. Attaching the small video for the same. Surely this feature is very much necessary across many apps and you will be enjoying using the same. The attached video will be helpful to visualize and enjoy it by simulating the same in your apps.
android
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Add Views Dynamically and Store Data in Arraylist in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java