How to implement swipe delete in android like iphone ?


Step 1: Just extends below class and implement getListview method.

Step 2: The below MainActivity demonstrates in which direction single item should be swiped and gives the item position of clicked item. We have to manage it in adapter to swipe-delete operation from our own scratch.

SwipeListViewActivity.java:

public abstract class SwipeListViewActivity extends Activity {

private ListView list;
private int REL_SWIPE_MIN_DISTANCE;
private int REL_SWIPE_MAX_OFF_PATH;
private int REL_SWIPE_THRESHOLD_VELOCITY;

/**
*
* @return ListView
*/
public abstract ListView getListView();

/**
*
* @param isRight
* Swiping direction
* @param position
* which item position is swiped
*/
public abstract void getSwipeItem(boolean isRight, int position);

/**
* For single tap/Click
*
* @param adapter
* @param position
*/
public abstract void onItemClickListener(ListAdapter adapter, int position);

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

DisplayMetrics dm = getResources().getDisplayMetrics();
REL_SWIPE_MIN_DISTANCE = (int) (120.0f * dm.densityDpi / 160.0f + 0.5);
REL_SWIPE_MAX_OFF_PATH = (int) (250.0f * dm.densityDpi / 160.0f + 0.5);
REL_SWIPE_THRESHOLD_VELOCITY = (int) (200.0f * dm.densityDpi / 160.0f + 0.5);
}

@Override
protected void onResume() {
super.onResume();
list = getListView();
if (list == null) {
new Throwable("Listview not set exception");
}

@SuppressWarnings("deprecation")
final GestureDetector gestureDetector = new GestureDetector(
new MyGestureDetector());

View.OnTouchListener gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
list.setOnTouchListener(gestureListener);

}

private void myOnItemClick(int position) {
if (position < 0)
return;
onItemClickListener(list.getAdapter(), position);

}

class MyGestureDetector extends SimpleOnGestureListener {

private int temp_position = -1;

// Detect a single-click and call my own handler.
@Override
public boolean onSingleTapUp(MotionEvent e) {

int pos = list.pointToPosition((int) e.getX(), (int) e.getY());
myOnItemClick(pos);
return true;
}

@Override
public boolean onDown(MotionEvent e) {

temp_position = list
.pointToPosition((int) e.getX(), (int) e.getY());
return super.onDown(e);
}

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
if (Math.abs(e1.getY() - e2.getY()) > REL_SWIPE_MAX_OFF_PATH)
return false;
if (e1.getX() - e2.getX() > REL_SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {

int pos = list
.pointToPosition((int) e1.getX(), (int) e2.getY());

if (pos >= 0 && temp_position == pos)
getSwipeItem(false, pos);
} else if (e2.getX() - e1.getX() > REL_SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > REL_SWIPE_THRESHOLD_VELOCITY) {

int pos = list
.pointToPosition((int) e1.getX(), (int) e2.getY());
if (pos >= 0 && temp_position == pos)
getSwipeItem(true, pos);

}
return false;
}

}

}
<h3>

MainActivity.java:

public class MainActivity extends SwipeListViewActivity {

private ListView mListView;
 private ArrayAdapter<String> mAdapter;

@Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 mListView = (ListView) findViewById(R.id.listView1);
 mAdapter = new ArrayAdapter<String>(this,
 android.R.layout.simple_list_item_1, new String[] { "Item 1",
 "Item 2", "Item 2", "Item 3", "Item 4", "Item 5" });
 mListView.setAdapter(mAdapter);
 }

@Override
 public ListView getListView() {
 return mListView;
 }

@Override
 public void getSwipeItem(boolean isRight, int position) {
 Toast.makeText(this,
 "Swipe to " + (isRight ? "right" : "left") + " direction",
 Toast.LENGTH_SHORT).show();
 }

@Override
 public void onItemClickListener(ListAdapter adapter, int position) {
 Toast.makeText(this, "Single tap on item position " + position,
 Toast.LENGTH_SHORT).show();
 }

}

Get the source code from the following link .
Let you comment on posts and encourage me for nice posts in future…

How to use listview in Dialog ?


1.First declare AlertDialog reference
AlertDialog dialog;

2.Second thing is you have to create an instance for AlertDialog.Builder
AlertDialog.Builder builder=new AlertDialog.Builder(this);

3.Set the title whatever you want and Here important thing is
AlertDialog.Builder should set the view .
4.The following code is in onCreate Method.Here CustomListAdapter is Adapter class which extends BaseAdapter for the custom view.

Button btn=(Button) findViewById(R.id.button1);
 btn.setText("Listview in Dialog");
   btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
   AlertDialog.Builder builder=new AlertDialog.Builder(DialogWithListviewActivity.this);
   builder.setTitle("Flowers");
   ListView list=new ListView(DialogWithListviewActivity.this);
   list.setAdapter(new CustomListAdapter(DialogWithListviewActivity.this));
   list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
     public void onItemClick(AdapterView<?> arg0, View arg1,
        int position, long arg3) {
         // TODO Auto-generated method stub
       if(dialog.isShowing())
         {
           dialog.dismiss();
          }
      Toast.makeText(mContext, "Clicked at Position"+position, Toast.LENGTH_SHORT).show();
    }
                });
                builder.setView(list);
                dialog=builder.create();
                dialog.show();
            }
        });

5.CustomAdapter should be like this.

<pre>public class CustomListAdapter extends BaseAdapter {

    private Context mContext;
    private LayoutInflater inflator;
    final int[] images = { R.drawable.magnolia,
            R.drawable.orchid, R.drawable.rose,
             };
    public CustomListAdapter(Context context) {
        // TODO Auto-generated constructor stub
  this.mContext=context;
 this.inflator= (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return images.length;
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        MainListHolder mHolder;

        View v = convertView;
        if (convertView == null)
        {
            mHolder = new MainListHolder();

            v = inflator.inflate(R.layout.inflate, null);
            mHolder.image=  (ImageView) v.findViewById(R.id.imageView1);

            v.setTag(mHolder);
        } else {
            mHolder = (MainListHolder) v.getTag();
        }

        mHolder.image.setImageResource(images[position]);
        mHolder.image.setPadding(20, 20, 20, 20);
        return v;
    }
    class MainListHolder
    {
        private ImageView image;
    }

}

I hope that this is useful for someone and download example here