Android Tip: making a draggable GridView by using external library

    Sometimes, to making our applications more vividly, we should create some special effects. Like in list views or grid views, drag and drop effects can make users to feel exciting. Through this small tip, I would like to present a simple way to create this effect by an external library. Now, you can follow step by step to complete your project.
    DEMO VIDEO:

Importing library

    By searching on Internet, you can find out that there are a lot of available library can help you in this problem. In this post, I will present DynamicGrid - a library written by Alex Askerov, it can run in any Froyo devices (API 8) or higher.
    Firstly, download it from @Github and after extracting it, you will see dynamicgrid folder:
    Importing this folder as an Android Studio project module to use it (see this post to learn about import project as module dependency for details). After finish this process, you can see the dynamicgrid module in your project:

     And your app/build.gradle look like this:
build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "info.devexchanges.draggablegridview"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile project(':dynamicgrid')
}

Declaring in layout file (xml)

    This library provide a drag and drop GridView through DynamicGridView class. So, put it in xml file:
activity_main.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="match_parent"
    android:orientation="vertical">

    <org.askerov.dynamicgrid.DynamicGridView
        android:id="@+id/dynamic_grid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="3" />

</LinearLayout>

Customizing GridView adapter

    You must customizing a GridView adapter based on  AbstractDynamicGridAdapter or BaseDynamicGridAdapter, this is the most important step to make the draggable GridView:
GridViewAdapter.java
package info.devexchanges.draggablegridview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.askerov.dynamicgrid.BaseDynamicGridAdapter;

import java.util.List;

public class GridViewAdapter extends BaseDynamicGridAdapter {

    public GridViewAdapter(Context context, List<?> items, int columnCount) {
        super(context, items, columnCount);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_grid, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.build(getItem(position).toString());
        return convertView;
    }

    private class ViewHolder {
        private TextView letterText;

        private ViewHolder(View view) {
            letterText = (TextView) view.findViewById(R.id.text);
        }

        void build(String title) {
            letterText.setText(title);
        }
    }
}
    Now, in Activity code, the drag and drop effect will active after call:
gridView.startEditMode();
or from onItemClick() and onItemLongClick():
gridView.startEditMode(position);
    Stopping this efftect by invoking this code:
gridView.stopEditMode();
    In this sample project, I active this effect after long click at any grid view item, I also handle their normal click event, full code:
MainActivity.java
package info.devexchanges.draggablegridview;

import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;

import org.askerov.dynamicgrid.DynamicGridView;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private DynamicGridView gridView;
    private String[] someViEnAlphabets= {"A", "Ă", "Â", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "Ô", "Ơ", "P", "Q", "R", "S", "T", "U", "V", "X", "Y"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        gridView = (DynamicGridView) findViewById(R.id.dynamic_grid);

        ArrayList arrayList = new ArrayList<>(Arrays.asList(someViEnAlphabets));

        GridViewAdapter gridViewAdpter = new GridViewAdapter(this, arrayList, 3);
        gridView.setAdapter(gridViewAdpter);

        //Active dragging mode when long click at each Grid view item
        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
                gridView.startEditMode(position);

                return true;
            }
        });

        //Handling click event of each Grid view item
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("Item information")
                        .setMessage("You clicked at position: " + position +"\n"
                                + "The letter is: " + parent.getItemAtPosition(position).toString())
                        .setPositiveButton(android.R.string.yes, null)

                        .setIcon(android.R.drawable.ic_dialog_info)
                        .show();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (gridView.isEditMode()) {
            gridView.stopEditMode();
        } else {
            super.onBackPressed();
        }
    }
}
    Layout for each grid view item (xml):
item_grid.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="match_parent"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableTop="@mipmap/ic_launcher"
        android:gravity="center"
        android:textStyle="bold" />

</LinearLayout>

Running Application

    After running this project, long click at each item, you can drag and drop it to new position:
    And when click at each item, an alert dialog will be shown:

Final thoughts

As note above, you can find out another libraries that similar with this to make a draggable grid view. For example:  DraggableGridView. From now, you can visit this tag link to read more post about GridView in Android. Finally, you can take my project on @Github.


Share


Previous post
« Prev Post
Next post
Next Post »