Open In App

SlidingDrawer in Android with Example

Last Updated : 22 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 Sliding Drawer which is used to hide the content out from 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. The 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. 

Important Methods of SlidingDrawer

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, using that lets us have a small demo code. Besides, those other important methods are also there and they are also discussed here. To initialize(or instantiate) a variable of SlidingDrawer, we need to do like below

// 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 next

SlidingDrawer simpleSlidingDrawer1 = (SlidingDrawer) findViewById (R.id.simpleSlidingDrawer1); 

Methods

Description

open() In order to open the drawer immediately, we open the drawer on View click (Button, TextView, etc)
close() In order to close the drawer immediately, we close the drawer on View click ( Button, TextView, etc)
animateOpen()

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)

animateClose()

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)

isOpened()

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

lock()

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)

unlock()

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)

// open the Sliding Drawer
simpleSlidingDrawer1.open(); 

// close the Sliding Drawer
simpleSlidingDrawer1.close(); 

// open the Sliding Drawer but with an animation
simpleSlidingDrawer1.animateOpen(); 

// close the Sliding Drawer but with an animation
simpleSlidingDrawer1.animateClose(); 

Programmatically we may need to check whether the SlidingDrawer is opened or closed. For that, we can use the below set of methods.

// check whether the slider is opened or not and depends
// upon that we can do rest of the calculations
Boolean isSliderSrawerOpen = simpleSlidingDrawer1.isOpened(); 

// If we do not want touch events to occur, set this
simpleSlidingDrawer1.lock(); 

// In order to process the touch events if accidentally
// locked or due to some requirement got locked
simpleSlidingDrawer1.unlock();

Setter Methods

setOnDrawerCloseListener(OnDrawerCloseListener onDrawerCloseListener)

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. 

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(OnDrawerOpenListener onDrawerOpenListener)

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.

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.

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.
        }
});

Important Attributes of SlidingDrawer

In order to identify a SliderDrawer, certain attributes are very mandatory. 

Attributes

Description
Id

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

handle

This attribute is used as an Identifier for the child that represents the drawer’s handle. 

This is always visible in the application

content

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.

orientation

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.

rotation Depending upon the requirement the view differs. Some prefer to have it in 90/180/270/360 degrees etc.

Example

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.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

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 current, 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>


Creating 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 3: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity 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 = 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 = findViewById(R.id.handle1);
  
        // initiate the ListView that is used for content of SlidingDrawer 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 = findViewById(R.id.simpleListView1);
  
        // Below syntax is for defining ArrayAdapter
        ArrayAdapter<String> cryptocurrencyArrayAdapter = new ArrayAdapter<>(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(() -> {
            // 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(() -> {
            // if close is done, we should have the option to open. according
            // to the requirement, carry out necessary steps for close
            handleButton.setText("Open");
        });
    }
}


Kotlin




package com.gfg.android.examplekotlin
  
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
  
class MainActivity : AppCompatActivity() {
    var nameArray = arrayOf("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 fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // initiate the SlidingDrawer
        val simpleSlidingDrawer1 = findViewById<SlidingDrawer>(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
        val handleButton = findViewById<Button>(R.id.handle1)
  
        // initiate the ListView that is used for content of SlidingDrawer 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
        val simpleListView1 = findViewById<ListView>(R.id.simpleListView1)
  
        // Below syntax is for defining ArrayAdapter
        val cryptocurrencyArrayAdapter = ArrayAdapter(applicationContext, R.layout.list_item, R.id.name1, nameArray)
  
        // set an adapter to fill the data in the ListView
        simpleListView1.adapter = cryptocurrencyArrayAdapter
  
        // implement setOnDrawerOpenListener event, name itself suggests that
        // we need to write code for drawer opening
        simpleSlidingDrawer1.setOnDrawerOpenListener {
            // 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.text = "Close"
        }
  
        // implement setOnDrawerCloseListener event, name itself suggests we need to write close events
        simpleSlidingDrawer1.setOnDrawerCloseListener {
            // if close is done, we should have the option to open. according
            // to the requirement, carry out necessary steps for close
            handleButton.text = "Open"
        }
    }
}


Output: Run on Emulator

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads