栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android滑动删除数据功能的实现代码

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap

Android滑动删除数据功能的实现代码

今天学习了新的功能那就是滑动删除数据。先看一下效果

我想这个效果大家都很熟悉吧。是不是在qq上看见过这个效果。俗话说好记性不如赖笔头,为了我的以后,为了跟我一样自学的小伙伴们,我把我的代码粘贴在下面。

activity_lookstaff.xml


   
  
  

delete_btn.xml



   

d_delete_btn.xml



  
  
  

DeleteListView .java

package com.rjxy.view;
import com.rjxy.activity.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
public class DeleteListView extends ListView
{
  private static final String TAG = "DeleteListView";
  
  private int touchSlop;
  
  private boolean isSliding;
  
  private int xDown;
  
  private int yDown;
  
  private int xMove;
  
  private int yMove;
  private LayoutInflater mInflater;
  private PopupWindow mPopupWindow;
  private int mPopupWindowHeight;
  private int mPopupWindowWidth;
  private Button mDelBtn;
  
  private DelButtonClickListener mListener;
  
  private View mCurrentView;
  
  private int mCurrentViewPos;
  
  public DeleteListView(Context context, AttributeSet attrs)
  {
    super(context, attrs);
    mInflater = LayoutInflater.from(context);
    touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    View view = mInflater.inflate(R.layout.delete_btn, null);
    mDelBtn = (Button) view.findViewById(R.id.id_item_btn);
    mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT,
 LinearLayout.LayoutParams.WRAP_CONTENT);
    
    mPopupWindow.getContentView().measure(0, 0);
    mPopupWindowHeight = mPopupWindow.getContentView().getMeasuredHeight();
    mPopupWindowWidth = mPopupWindow.getContentView().getMeasuredWidth();
  }
  @Override
  public boolean dispatchTouchEvent(MotionEvent ev)
  {
    int action = ev.getAction();
    int x = (int) ev.getX();
    int y = (int) ev.getY();
    switch (action)
    {
    case MotionEvent.ACTION_DOWN:
      xDown = x;
      yDown = y;
      
      if (mPopupWindow.isShowing())
      {
 dismissPopWindow();
 return false;
      }
      // 获得当前手指按下时的item的位置
      mCurrentViewPos = pointToPosition(xDown, yDown);
      // 获得当前手指按下时的item
      View view = getChildAt(mCurrentViewPos - getFirstVisiblePosition());
      mCurrentView = view;
      break;
    case MotionEvent.ACTION_MOVE:
      xMove = x;
      yMove = y;
      int dx = xMove - xDown;
      int dy = yMove - yDown;
      
      if (xMove < xDown && Math.abs(dx) > touchSlop && Math.abs(dy) < touchSlop)
      {
 // Log.e(TAG, "touchslop = " + touchSlop + " , dx = " + dx +
 // " , dy = " + dy);
 isSliding = true;
      }
      break;
    }
    return super.dispatchTouchEvent(ev);
  }
  @Override
  public boolean onTouchEvent(MotionEvent ev)
  {
    int action = ev.getAction();
    
    if (isSliding)
    {
      switch (action)
      {
      case MotionEvent.ACTION_MOVE:
 int[] location = new int[2];
 // 获得当前item的位置x与y
 mCurrentView.getLocationOnScreen(location);
 // 设置popupWindow的动画
 mPopupWindow.setAnimationStyle(R.style.popwindow_delete_btn_anim_style);
 mPopupWindow.update();
 mPopupWindow.showAtLocation(mCurrentView, Gravity.LEFT | Gravity.TOP,
     location[0] + mCurrentView.getWidth(), location[1] + mCurrentView.getHeight() / 2
  - mPopupWindowHeight / 2);
 // 设置删除按钮的回调
 mDelBtn.setonClickListener(new onClickListener()
 {
   @Override
   public void onClick(View v)
   {
     if (mListener != null)
     {
mListener.clickHappend(mCurrentViewPos);
mPopupWindow.dismiss();
     }
   }
 });
 // Log.e(TAG, "mPopupWindow.getHeight()=" + mPopupWindowHeight);
 break;
      case MotionEvent.ACTION_UP:
 isSliding = false;
      }
      // 相应滑动期间屏幕itemClick事件,避免发生冲突
      return true;
    }
    return super.onTouchEvent(ev);
  }
  
  private void dismissPopWindow()
  {
    if (mPopupWindow != null && mPopupWindow.isShowing())
    {
      mPopupWindow.dismiss();
    }
  }
  public void setDelButtonClickListener(DelButtonClickListener listener)
  {
    mListener = listener;
  }
  public interface DelButtonClickListener
  {
    public void clickHappend(int position);
  }
}

DeleteStaffActivity .java

package com.rjxy.activity;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.rjxy.bean.Staff;
import com.rjxy.path.Path;
import com.rjxy.util.StreamTools;
import com.rjxy.view.DeleteListView;
import com.rjxy.view.DeleteListView.DelButtonClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class DeleteStaffActivity extends Activity {
  private static final int CHANGE_UI = 1;
  private static final int DELETE = 3;
  private static final int SUCCESS = 2;
  private static final int ERROR = 0;
  private DeleteListView lv;
  private ArrayAdapter mAdapter;
  private List staffs = new ArrayList();
  private Staff staff;
  String sno;
  // 主线程创建消息处理器
  private Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
      if (msg.what == CHANGE_UI) {
 try {
   JSonArray arr = new JSonArray((String) msg.obj);
   for (int i = 0; i < arr.length(); i++) {
     JSonObject temp = (JSONObject) arr.get(i);
     staff = new Staff();
     staff.setSno(temp.getString("sno"));
     staff.setSname(temp.getString("sname"));
     staff.setDname(temp.getString("d_name"));
     staffs.add("员工号:" + staff.getSno() + "n姓  名:"
  + staff.getSname() + "n部  门:" + staff.getDname());
   }
   mAdapter = new ArrayAdapter(
DeleteStaffActivity.this,
android.R.layout.simple_list_item_1, staffs);
   lv.setAdapter(mAdapter);
   lv.setDelButtonClickListener(new DelButtonClickListener() {
     @Override
     public void clickHappend(final int position) {
String s = mAdapter.getItem(position);
String[] ss = s.split("n");
String snos = ss[0];
String[] sss = snos.split(":");
sno = sss[1];
delete();
mAdapter.remove(mAdapter.getItem(position));
     }
   });
   lv.setonItemClickListener(new onItemClickListener() {
     @Override
     public void onItemClick(AdapterView parent,
  View view, int position, long id) {
Toast.makeText(
    DeleteStaffActivity.this,
    position + " : "
 + mAdapter.getItem(position), 0)
    .show();
     }
   });
 } catch (JSonException e) {
   e.printStackTrace();
 }
      } else if (msg.what == DELETE) {
 Toast.makeText(DeleteStaffActivity.this, (String) msg.obj, 1)
     .show();
      }
    };
  };
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lookstaff);
    lv = (DeleteListView) findViewById(R.id.id_listview);
    select();
  }
  private void select() {
    // 子线程更新UI
    new Thread() {
      public void run() {
 try {
   // 区别1、url的路径不同
   URL url = new URL(Path.lookStaffPath);
   HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
   // 区别2、请求方式post
   conn.setRequestMethod("POST");
   conn.setRequestProperty("User-Agent",
"Mozilla/5.0(compatible;MSIE 9.0;Windows NT 6.1;Trident/5.0)");
   // 区别3、必须指定两个请求的参数
   conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");// 请求的类型 表单数据
   String data = "";
   conn.setRequestProperty("Content-Length", data.length()
+ "");// 数据的长度
   // 区别4、记得设置把数据写给服务器
   conn.setDoOutput(true);// 设置向服务器写数据
   byte[] bytes = data.getBytes();
   conn.getOutputStream().write(bytes);// 把数据以流的方式写给服务器
   int code = conn.getResponseCode();
   System.out.println(code);
   if (code == 200) {
     InputStream is = conn.getInputStream();
     String result = StreamTools.readStream(is);
     Message mas = Message.obtain();
     mas.what = CHANGE_UI;
     mas.obj = result;
     handler.sendMessage(mas);
   } else {
     Message mas = Message.obtain();
     mas.what = ERROR;
     handler.sendMessage(mas);
   }
 } catch (IOException e) {
   // TODO Auto-generated catch block
   Message mas = Message.obtain();
   mas.what = ERROR;
   handler.sendMessage(mas);
 }
      }
    }.start();
  }
  private void delete() {
    // 子线程更新UI
    new Thread() {
      public void run() {
 try {
   // 区别1、url的路径不同
   URL url = new URL(Path.deleteStaffPath);
   HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
   // 区别2、请求方式post
   conn.setRequestMethod("POST");
   conn.setRequestProperty("User-Agent",
"Mozilla/5.0(compatible;MSIE 9.0;Windows NT 6.1;Trident/5.0)");
   // 区别3、必须指定两个请求的参数
   conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");// 请求的类型 表单数据
   String data = "sno=" + sno;
   conn.setRequestProperty("Content-Length", data.length()
+ "");// 数据的长度
   // 区别4、记得设置把数据写给服务器
   conn.setDoOutput(true);// 设置向服务器写数据
   byte[] bytes = data.getBytes();
   conn.getOutputStream().write(bytes);// 把数据以流的方式写给服务器
   int code = conn.getResponseCode();
   System.out.println(code);
   if (code == 200) {
     InputStream is = conn.getInputStream();
     String result = StreamTools.readStream(is);
     Message mas = Message.obtain();
     mas.what = DELETE;
     mas.obj = result;
     handler.sendMessage(mas);
   } else {
     Message mas = Message.obtain();
     mas.what = ERROR;
     handler.sendMessage(mas);
   }
 } catch (IOException e) {
   // TODO Auto-generated catch block
   Message mas = Message.obtain();
   mas.what = ERROR;
   handler.sendMessage(mas);
 }
      }
    }.start();
  }
}

以上所述是小编给大家介绍的Android滑动删除数据功能的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/160126.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号