Swipeable ListView in Android

Follow the bellow steps to create a Swipeable ListView in Android  .

Step 1: Create Project 
          a) Open Android Studio
          b) Go to File >New> New Project  > Project Name  > Next > Next > Next > Finish 
  
Step 2: Add Design Library

   Open build.gradle > add this line compile "com.daimajia.swipelayout:library:1.2.0@aar"
    > Sync the gradle file . 
Like this 
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

     compile 'com.android.support:appcompat-v7:23.4.0'
     compile 'com.daimajia.swipelayout:library:1.2.0@aar'
}
If Gradle doesn’t automatically ask you to sync your project, open module 'app' from the Build menu or press F9. By doing so, the Android Studio build system will automatically fetch the necessary resources and you will be able to import any required classes.

Step 3 : Layout Design 
open activity_main.xml file and add the bellow code 

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="sutopa.swipeablelistview.MainActivity">

    <ListView
        android:id="@+id/list_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>
 Step 4 : Create a file "header.xml" and add the bellow code

     <?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/bottom_wrapper"
        android:layout_width="80dp"
        android:layout_height="match_parent"
        android:background="#FF33FF"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/total"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:minHeight="?android:attr/listPreferredItemHeightSmall"
            android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
            android:paddingRight="?android:attr/listPreferredItemPaddingRight"
            android:textAppearance="?android:attr/textAppearanceListItemSmall" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#895623"
        android:padding="10dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="Total Language"
            android:textAllCaps="true"
            android:textColor="@android:color/white"
            android:textStyle="bold" />

    </LinearLayout>
</com.daimajia.swipe.SwipeLayout>

  Step 5 : Create a file "item.xml" and add the bellow code

   <?xml version="1.0" encoding="utf-8"?>
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Bottom View Start-->
    <LinearLayout
        android:id="@+id/bottom_wrapper"
        android:layout_width="100dp"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#66ddff00">

            <ImageView
                android:id="@+id/edit_query"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:src="@drawable/edit" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="#66FF3300">

            <ImageView
                android:id="@+id/delete"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:src="@drawable/delete" />
        </RelativeLayout>


    </LinearLayout>
    <!-- Bottom View End-->

    <!-- Surface View Start -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#575757"
        android:padding="10dp">

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:textColor="#FFFFFF"
            android:text=""
            android:minHeight="?android:attr/listPreferredItemHeightSmall"
            android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
            android:paddingRight="?android:attr/listPreferredItemPaddingRight"
            android:textAppearance="?android:attr/textAppearanceListItemSmall" />
    </LinearLayout>
    <!-- Surface View End -->
</com.daimajia.swipe.SwipeLayout>

Step 6 : Create a class "ListViewAdapter.java" which extends ArrayAdapter<String> class and add the bellow code.

   import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.daimajia.swipe.SwipeLayout;

import java.util.List;

/**
 * Created by anupam on 20/10/16.
 */
public class ListViewAdapter extends ArrayAdapter<String> {

    private MainActivity activity;
    private List<String> friends;


    public ListViewAdapter(MainActivity context, int resource, List<String> objects) {
        super(context, resource, objects);
        this.activity = context;
        this.friends = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) activity
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.item, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }

        holder.name.setText(getItem(position));

        //handling buttons event
        holder.btnEdit.setOnClickListener(onEditListener(position, holder));
        holder.btnDelete.setOnClickListener(onDeleteListener(position, holder));

        return convertView;
    }

    private View.OnClickListener onEditListener(final int position, final ViewHolder holder) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showEditDialog(position, holder);
            }
        };
    }

    /**
     * Editting confirm dialog
     * @param position
     * @param holder
     */
    private void showEditDialog(final int position, final ViewHolder holder) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);

        alertDialogBuilder.setTitle("EDIT");
        final EditText input = new EditText(activity);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        input.setText(friends.get(position));
        input.setLayoutParams(lp);
        alertDialogBuilder.setView(input);

        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // get user input and set it to result edit text
                                friends.set(position, input.getText().toString().trim());

                                //notify data set changed
                                activity.updateAdapter();
                                holder.swipeLayout.close();
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        // create alert dialog and show it
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    private View.OnClickListener onDeleteListener(final int position, final ViewHolder holder) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                friends.remove(position);
                holder.swipeLayout.close();
                activity.updateAdapter();
            }
        };
    }

    private class ViewHolder {
        private TextView name;
        private View btnDelete;
        private View btnEdit;
        private SwipeLayout swipeLayout;

        public ViewHolder(View v) {
            swipeLayout = (SwipeLayout)v.findViewById(R.id.swipe_layout);
            btnDelete = v.findViewById(R.id.delete);
            btnEdit = v.findViewById(R.id.edit_query);
            name = (TextView) v.findViewById(R.id.name);

            swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);
        }
    }
}

Step 7 : Create a class "MainActivity.java" which extends Activity class and add the bellow code.

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.daimajia.swipe.SwipeLayout;
import java.util.ArrayList;

public class MainActivity extends Activity {
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private ArrayList<String> LanguageList;
    private TextView totalClassmates;
    private SwipeLayout swipeLayout;
    private final static String TAG = MainActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView)findViewById(R.id.list_item);

        LanguageList = new ArrayList<>();
        getDataFromFile();
        setListViewHeader();
        setListViewAdapter();
    }

    public void updateAdapter() {
        adapter.notifyDataSetChanged(); //update adapter
        totalClassmates.setText("(" + LanguageList.size() + ")"); //update total friends in list
    }

    private void getDataFromFile() {
        LanguageList.add("English");
        LanguageList.add("Hindi");
        LanguageList.add("Bengali");
        LanguageList.add("Spanish");
        LanguageList.add("Marathi");
        LanguageList.add("Gujarati");
        LanguageList.add("Bhojpuri");

    }

    private void setListViewHeader() {
        LayoutInflater inflater = getLayoutInflater();
        View header = inflater.inflate(R.layout.header, listView, false);
        totalClassmates = (TextView) header.findViewById(R.id.total);
        swipeLayout = (SwipeLayout)header.findViewById(R.id.swipe_layout);
        setSwipeViewFeatures();
        listView.addHeaderView(header);
    }

    private void setSwipeViewFeatures() {
        //set show mode.
        swipeLayout.setShowMode(SwipeLayout.ShowMode.PullOut);

        //add drag edge.(If the BottomView has 'layout_gravity' attribute, this line is unnecessary)
        swipeLayout.addDrag(SwipeLayout.DragEdge.Left, findViewById(R.id.bottom_wrapper));

        swipeLayout.addSwipeListener(new SwipeLayout.SwipeListener() {
            @Override
            public void onClose(SwipeLayout layout) {
              
            }

            @Override
            public void onUpdate(SwipeLayout layout, int leftOffset, int topOffset) {
               
            }

            @Override
            public void onStartOpen(SwipeLayout layout) {
               
            }

            @Override
            public void onOpen(SwipeLayout layout) {
               
            }

            @Override
            public void onStartClose(SwipeLayout layout) {
               
            }

            @Override
            public void onHandRelease(SwipeLayout layout, float xvel, float yvel) {
               
            }
        });
    }

    private void setListViewAdapter() {
        adapter = new ListViewAdapter(this, R.layout.item_listview, LanguageList);
        listView.setAdapter(adapter);

        totalClassmates.setText("(" + LanguageList.size() + ")");
    }

}
Find Us : 
        Facebook : @apnaandroid
        Google+   : Apna Java
        Youtube : Android & Java Tutorial
Output ::
                           

Comments

Popular posts from this blog

Custom Calendar in android

Disable/Hide Year from DatePickerDialog in android

Coordinator Layout in Android