Thursday 25 September 2014

Drag and Drop into two gridview

1) Create a MainActivity.java


package com.game.wordgame;

import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipData.Item;
import android.content.ClipDescription;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.example.wordgame.R;

public class MainActivity extends Activity {
    private BottomGridAdapter mBottomGridAdapter;
    private LinearLayout bottomLayout, topLayout;
    private TopGridAdapter mTopGridAdapter;
    private GridView gridViewTop, gridViewBottom;
    private ArrayList<String> alstTop;
    private ArrayList<String> alstTopPoints;
    private ArrayList<String> alstBottom;
    private ArrayList<String> alstBottomPoints;
    int intTopPos, intBottomPos;
    private String strTopItem, strTopItemPoints;
    private String strBottomItem, strBottomItemPoints;
    public boolean boolGridTop = true;
    MyDragListener myDragListener = new MyDragListener();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alstTop = new ArrayList<String>();
        alstTopPoints = new ArrayList<String>();
        for (int i = 0; i <= 169; i++) {
            if (i == 57) {
                alstTop.add("T");
                alstTopPoints.add("1");
            } else if (i == 58) {
                alstTop.add("H");
                alstTopPoints.add("2");
            } else if (i == 59) {
                alstTop.add("E");
                alstTopPoints.add("3");
            } else {
                alstTop.add("");
                alstTopPoints.add("");
            }
        }

        bottomLayout = (LinearLayout) findViewById(R.id.bottomlayout);
        topLayout = (LinearLayout) findViewById(R.id.toplayout);
        gridViewTop = (GridView) findViewById(R.id.top_gridview);
        mTopGridAdapter = new TopGridAdapter(this, alstTop, alstTopPoints);
        gridViewTop.setAdapter(mTopGridAdapter);
        gridViewTop.setOnItemLongClickListener(gridTopClickListener);

        gridViewBottom = (GridView) findViewById(R.id.bottom_gridview);
        gridViewBottom.setOnItemLongClickListener(gridBottomClickListener);

        alstBottom = new ArrayList<String>();
        alstBottomPoints = new ArrayList<String>();
        alstBottom.add("A");
        alstBottom.add("B");
        alstBottom.add("C");
        alstBottom.add("D");
        alstBottom.add("E");
        alstBottom.add("F");
        alstBottom.add("G");
        for (int i = 0; i < 7; i++) {
            alstBottomPoints.add("" + i);
        }

        mBottomGridAdapter = new BottomGridAdapter(this, alstBottom,alstBottomPoints);
        gridViewBottom.setAdapter(mBottomGridAdapter);
        gridViewTop.setOnDragListener(myDragListener);
        bottomLayout.setOnDragListener(myDragListener);
        gridViewBottom.setOnDragListener(myDragListener);
        topLayout.setOnDragListener(myDragListener);
    }

    OnItemLongClickListener gridTopClickListener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> l, View v, int Position,long id){
            intTopPos = Position;
            boolGridTop = true;
            // Selected item is passed as item in dragData
            ClipData.Item item = new ClipData.Item(alstTop.get(Position)
                    + alstTopPoints.get(Position));
            String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
            ClipData dragData = new ClipData((CharSequence) v.getTag(),
                    clipDescription, item);

            DragShadowBuilder myShadow = new MyDragShadowBuilder(v, Position);
            v.startDrag(dragData, myShadow, alstTop.get(Position), 0);

            strTopItem = alstTop.get(Position);
            strTopItemPoints = alstTopPoints.get(Position);
            Log.i("strTopItem", "strTopItem==>>" + strTopItem);
            Log.i("strTopPoints", "strTopPoints==>>" + strTopItemPoints);

            alstTop.remove(intTopPos);
            alstTop.add(intTopPos, "");

            alstTopPoints.remove(intTopPos);
            alstTopPoints.add(intTopPos, "");
            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,
                    alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
            Log.i("", "intTopPos ===>>>>" + intTopPos);
            return true;
        }
    };

    OnItemLongClickListener gridBottomClickListener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> l, View v, int Position,long id) {
            // Selected item is passed as item in dragData
            boolGridTop = false;
            intBottomPos = Position;
            ClipData.Item item = new ClipData.Item(alstBottom.get(Position)
                    + alstBottomPoints.get(Position));
            String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
            ClipData dragData = new ClipData((CharSequence) v.getTag(),
                    clipDescription, item);

            DragShadowBuilder myShadow = new MyDragShadowBuilder(v, Position);
            v.startDrag(dragData, myShadow, alstBottom.get(Position), 0);

            strBottomItem = alstBottom.get(Position);
            strBottomItemPoints = alstBottomPoints.get(Position);
            Log.i("strBottomItem", "strBottomItem==>>" + strBottomItem);
            Log.i("strBottomPoints", "strBottomPoints==>>" + strBottomItemPoints);

            alstBottom.remove(intBottomPos);
            alstBottom.add(intBottomPos, "");
            alstBottomPoints.remove(intBottomPos);
            alstBottomPoints.add(intBottomPos, "");

            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom, alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();

            return true;
        }
    };

    @SuppressLint("NewApi")
    private class MyDragShadowBuilder extends View.DragShadowBuilder {
        private Drawable shadow;

        public MyDragShadowBuilder(View view, int pos) {
            super(view);
            Log.d("TAG", "Building shadow.");
            shadow = getResources().getDrawable(R.drawable.tile1);

            shadow.setCallback(view);
            Log.i("view.getWidth()", "view.getWidth()==>>" + view.getWidth()/ 2);
            Log.i("getHeight", "getHeight==>>" + view.getHeight() / 2);
            shadow.setBounds(20, 20, view.getWidth() / 2, view.getHeight() / 2);
        }

        @Override
        public void onDrawShadow(Canvas canvas) {
            Log.d("TAG", "Drawing shadow.");
            shadow.draw(canvas);
            getView().draw(canvas);
        }
    }

    protected class MyDragListener implements View.OnDragListener {
        @Override
        public boolean onDrag(View v, DragEvent event) {
            final int action = event.getAction();
            switch (action) {
            case DragEvent.ACTION_DRAG_STARTED:
                // All involved view accept ACTION_DRAG_STARTED for
                // MIMETYPE_TEXT_PLAIN
                // Toast.makeText(MainActivity.this, "ACTION_DRAG_STARTED",
                // Toast.LENGTH_SHORT).show();
                // if (event.getClipDescription().hasMimeType(
                // ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                // return true;
                // } else {
                // return false; // reject
                // }

                return true;
            case DragEvent.ACTION_DRAG_ENTERED:

                return true;
            case DragEvent.ACTION_DRAG_LOCATION:

                return true;
            case DragEvent.ACTION_DRAG_EXITED:

                return true;
            case DragEvent.ACTION_DROP:
                // Toast.makeText(MainActivity.this, "ACTION_DROP",
                // Toast.LENGTH_SHORT).show();
                // Gets the item containing the dragged data
                // ClipData.Item item = event.getClipData().getItemAt(0);
                // If apply only if drop on buttonTarget
                if (v == bottomLayout) {
                    // String droppedItem = item.getText().toString();
                    if (boolGridTop) {
                        int newPosition = gridViewBottom.pointToPosition(
                                (int) (event.getX()), (int) event.getY());
                        Log.d("Position is==", Integer.toString(newPosition));
                        if (newPosition != ListView.INVALID_POSITION)
                            return processDropTopToBottom(event, newPosition);
                        else
                            return false;
                    } else {
                        int newPosition = gridViewBottom.pointToPosition(
                                (int) (event.getX()), (int) event.getY());
                        Log.d("Position is==", Integer.toString(newPosition));
                        if (newPosition != ListView.INVALID_POSITION)
                            return processDropBottomToBottom(event, newPosition);
                        else
                            return false;
                    }
                } else if (v == topLayout) {
                    if (boolGridTop) {
                        int newPosition = gridViewTop.pointToPosition(
                                (int) (event.getX()), (int) event.getY());
                        Log.d("Position is==", Integer.toString(newPosition));
                        if (newPosition != ListView.INVALID_POSITION)
                            return processDropTopToTop(event, newPosition);
                        else
                            return false;
                    } else{
                        int newPosition = gridViewTop.pointToPosition(
                                (int) (event.getX()), (int) event.getY());
                        Log.d("Position is==", Integer.toString(newPosition));
                        if (newPosition != ListView.INVALID_POSITION)
                            return processDropBottomToTop(event, newPosition);
                        else
                            return false;
                    }
                } else{
                    return false;
                }
            case DragEvent.ACTION_DRAG_ENDED:
                if (event.getResult()){
                } else {
                }
                ;
                return true;
            default:
                return false;
            }
        }
    }

    private boolean processDropTopToBottom(DragEvent event, int newPosition) {
        ClipData data = event.getClipData();
        if (data != null) {
            if (data.getItemCount() > 0) {
                Item item = data.getItemAt(0);
                String value = item.getText().toString();
                Log.i("New value", "New value==" + value);
                updateTopToBottomViewsAfterDropComplete(value, newPosition);
                return true;
            }
        }
        return false;
    }

    private boolean processDropTopToTop(DragEvent event, int newPosition) {
        ClipData data = event.getClipData();
        if (data != null) {
            if (data.getItemCount() > 0) {
                Item item = data.getItemAt(0);
                String value = item.getText().toString();
                updateTopToTopViewsAfterDropComplete(value, newPosition);
                return true;
            }
        }
        return false;
    }

    private boolean processDropBottomToTop(DragEvent event, int newPosition) {
        ClipData data = event.getClipData();
        if (data != null) {
            if (data.getItemCount() > 0) {
                Item item = data.getItemAt(0);
                String value = item.getText().toString();
                updateBottomToTopViewsAfterDropComplete(value, newPosition);
                return true;
            }
        }
        return false;
    }

    private boolean processDropBottomToBottom(DragEvent event, int newPosition) {
        ClipData data = event.getClipData();
        if (data != null) {
            if (data.getItemCount() > 0) {
                Item item = data.getItemAt(0);
                String value = item.getText().toString();
                updateBottomToBottomViewsAfterDropComplete(value, newPosition);
                return true;
            }
        }
        return false;
    }

    private void updateTopToBottomViewsAfterDropComplete(String listItem, int index) {
        String strBottom = "" + listItem.charAt(0);
        String strBottomPoins = listItem.substring(1);
       
        Log.i("", "alstBottom.get(index)===>>>"+alstBottom.get(index));
        if (alstBottom.get(index) == null || alstBottom.get(index).equalsIgnoreCase("")) {
            alstBottom.remove(index);
            alstBottom.add(index, strBottom);

            alstBottomPoints.remove(index);
            alstBottomPoints.add(index, strBottomPoins);

            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom,alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();
        }else{
            alstTop.remove(intTopPos);
            alstTop.add(intTopPos, strTopItem);

            alstTopPoints.remove(intTopPos);
            alstTopPoints.add(intTopPos, strBottomPoins);
            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,
                    alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
        }
    }

    private void updateTopToTopViewsAfterDropComplete(String listItem, int index){
        String strTop = "" + listItem.charAt(0);
        String strTopPoints = listItem.substring(1);

        if (alstTop.get(index) == null || alstTop.get(index).equals("")){
            alstTop.remove(index);
            alstTop.add(index, strTop);
            alstTopPoints.remove(index);
            alstTopPoints.add(index, strTopPoints);

            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
        } else{
            alstTop.remove(intTopPos);
            alstTop.add(intTopPos, strTopItem);
            alstTopPoints.remove(intTopPos);
            alstTopPoints.add(intTopPos, strTopItemPoints);

            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
        }
    }

    private void updateBottomToTopViewsAfterDropComplete(String listItem,int index) {
        Log.d("InsertItem", "Position: " + index);
        String strTop = "" + listItem.charAt(0);
        String strTopPoints = listItem.substring(1);
       
        if (alstTop.get(index) == null || alstTop.get(index).equals("")) {
            alstTop.remove(index);
            alstTop.add(index, strTop);

            alstTopPoints.remove(index);
            alstTopPoints.add(index, strTopPoints);

            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
           
        } else {
            alstBottom.remove(intBottomPos);
            alstBottom.add(intBottomPos, strBottomItem);

            alstBottomPoints.remove(intBottomPos);
            alstBottomPoints.add(intBottomPos, strBottomItemPoints);
            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom, alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();
        }
    }

    private void updateBottomToBottomViewsAfterDropComplete(String listItem,int index){
        String strBottom = "" + listItem.charAt(0);
        String strBottomPoins = listItem.substring(1);
        if (alstBottom.get(index) == null || alstBottom.get(index).equals("")) {
            alstBottom.remove(index);
            alstBottom.add(index, strBottom);

            alstBottomPoints.remove(index);
            alstBottomPoints.add(index, strBottomPoins);

            Log.i("", "" + alstBottom.toString());
            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom, alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();
   
        } else{
            alstBottom.remove(intBottomPos);
            alstBottom.add(intBottomPos, strBottomItem);

            alstBottomPoints.remove(intBottomPos);
            alstBottomPoints.add(intBottomPos, strBottomItemPoints);
            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom, alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();
        }
    }
}

2) Create BottomGridAdapter.java

package com.game.wordgame;

import java.util.ArrayList;
import com.example.wordgame.R;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class BottomGridAdapter extends BaseAdapter{
    private LayoutInflater mLayoutInflater = null;
    private Context mContext = null;
    private ArrayList<String> alstBottom;
    private ArrayList<String> alstBottomPoints;
   
    public BottomGridAdapter(Context mContext,ArrayList<String>alstBottom,ArrayList<String> alstBottomPoints){
        this.mContext = mContext;
        this.alstBottom = alstBottom;
        this.alstBottomPoints = alstBottomPoints;
        this.mLayoutInflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount(){
        Log.i("TAG", ""+alstBottom.size());
        return alstBottom.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position){
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = mLayoutInflater.inflate(R.layout.bottom_grid_adapter, null);
        TextView txtBottom = (TextView)convertView.findViewById(R.id.txtBottom);
        TextView txtBottomPoints = (TextView)convertView.findViewById(R.id.txtBottomPoints);
       
        txtBottomPoints.setText(alstBottomPoints.get(position));
        //txtBottom.setBackgroundResource(R.drawable.tile1);
        txtBottom.setText(alstBottom.get(position));
       
        if (TextUtils.equals(txtBottom.getText(), "")) {
            txtBottom.setBackgroundResource(R.drawable.transperent_icon);
        } else {
            txtBottom.setBackgroundResource(R.drawable.tilebig);
        }
        return convertView;
    }
}

3) Create TopGridAdapter.java
package com.game.wordgame;

import java.util.ArrayList;
import com.example.wordgame.R;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class TopGridAdapter extends BaseAdapter {
    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private ArrayList<String> alstTop;
    private ArrayList<String> alstTopPoints;

    public TopGridAdapter(Context mContext, ArrayList<String> alstTop,ArrayList<String> alstTopPoints) {
        this.mContext = mContext;
        this.mLayoutInflater = LayoutInflater.from(mContext);
        this.alstTop = alstTop;
        this.alstTopPoints = alstTopPoints;
    }

    @Override
    public int getCount() {
        return 169;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = mLayoutInflater.inflate(R.layout.top_grid_adapter, null);

        TextView txtTop = (TextView) convertView.findViewById(R.id.txtTop);
        TextView txtTopPoints = (TextView)convertView.findViewById(R.id.txtTopPoints);
        txtTopPoints.setText(alstTopPoints.get(position));
        txtTop.setText("" + alstTop.get(position));
       
        if (TextUtils.equals(txtTop.getText(), "")) {
            txtTop.setBackgroundResource(R.drawable.transperent_icon);
        } else {
            txtTop.setBackgroundResource(R.drawable.tile1);
        }
        return convertView;
    }
}

4)create activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/toplayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:orientation="vertical" >
        <GridView
            android:id="@+id/top_gridview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/board"
            android:gravity="center"
            android:numColumns="13"
            android:stretchMode="columnWidth" >
        </GridView>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/bottomlayout"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_below="@id/toplayout"
        android:orientation="vertical">
        <GridView
            android:id="@+id/bottom_gridview"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:gravity="top"
            android:layout_gravity="top"
            android:layout_marginTop="@dimen/grid_bottom_margin"
            android:numColumns="7"
            android:padding="@dimen/bottom_grid_margin" >
        </GridView>
    </LinearLayout>
</RelativeLayout>

5) Create bottom_grid_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txtBottom"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:background="@drawable/tile_bg"
        android:contentDescription="@string/app_name"
        android:gravity="center"
        android:text="a"
        android:textSize="@dimen/b_cell_textsize"
        android:textStyle="bold"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/txtBottomPoints"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|right"
        android:padding="10dp"
        android:text="1"
        android:textSize="@dimen/b_cell_point_size"
        android:textColor="@android:color/black" />
</FrameLayout>

6) top_grid_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:orientation="vertical" >
<!--     <TextView -->
<!--         android:id="@+id/imgCellTop" -->
<!--         android:layout_width="30dp" -->
<!--         android:layout_height="30dp" -->
<!--         android:contentDescription="@string/app_name" -->
<!--         android:layout_gravity="center" -->
<!--         android:gravity="center" -->
<!--         android:textColor="@android:color/black"/> -->
    <TextView
        android:id="@+id/txtTop"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:background="@drawable/tile1"
        android:contentDescription="@string/app_name"
        android:gravity="center"
        android:text="a"
        android:padding="2dp"
        android:textSize="@dimen/t_cell_textdize"
        android:textStyle="bold"
        android:textColor="@android:color/black" />
    <TextView
        android:id="@+id/txtTopPoints"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|right"
        android:padding="2dp"
        android:text="1"
        android:textSize="@dimen/t_cell_point_size"
        android:textColor="@android:color/black" />
</FrameLayout>