After a couple of times when i was requested to make a drag and drop UI for a client.
After countless hours of searching in which i came up with 20 examples of implementation by way of surface views and bitmaps (an implementation that i really didn't like), and all the while i see countless comments of frustrated people with the same problem as me, i decided to implement this my way and then release it back so that at least once this solution will be in public domain.
so, i hope this helps someone.
[syntax="java"]
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.FrameLayout.LayoutParams;
public class dnd extends Activity
{
public FrameLayout board;
public View pawn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
board = new FrameLayout(this);
pawn = new View(this);
setContentView(R.layout.main);
board = (FrameLayout)findViewById(R.id.Board);
pawn = findViewById(R.id.Pawn);
pawn.setOnTouchListener(dragt);
}//onCreate
OnTouchListener dragt = new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
FrameLayout.LayoutParams par = (LayoutParams) v.getLayoutParams();
switch(v.getId())
{//What is being touched
case R.id.Pawn:
{//Which action is being taken
switch(event.getAction())
{
case MotionEvent.ACTION_MOVE:
{
par.topMargin = (int)event.getRawY() - (v.getHeight());
par.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
v.setLayoutParams(par);
break;
}//inner case MOVE
case MotionEvent.ACTION_UP:
{
par.height = 40;
par.width = 40;
par.topMargin = (int)event.getRawY() - (v.getHeight());
par.leftMargin = (int)event.getRawX() - (v.getWidth()/2);
v.setLayoutParams(par);
break;
}//inner case UP
case MotionEvent.ACTION_DOWN:
{
par.height = 60;
par.width = 60;
v.setLayoutParams(par);
break;
}//inner case UP
}//inner switch
break;
}//case pawn
}//switch
return true;
}//onTouch
};//dragt
}
[syntax="xml"]
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/Board" android:layout_gravity="top">
<View android:background="@drawable/icon"
android:layout_height="40dp"
android:layout_width="40dp"
android:id="@+id/Pawn" android:layout_gravity="top">
</View>
</FrameLayout>


.