Android 슬라이딩 데이터 삭제 기능 구현 코드

오늘 새로운 기능 을 배 웠 습 니 다.일단 효 과 를 볼 게 요.


나 는 이 효과 가 모두 가 잘 알 고 있 을 것 이 라 고 생각한다.qq 에서 이 효 과 를 본 적 이 있 습 니까?기억력 은 붓끝 에 달 라 붙 는 것 보다 못 하 다 는 속담 이 있 습 니 다.저 를 위해 앞으로 저 처럼 독학 하 는 친구 들 을 위해 제 코드 를 아래 에 붙 여 놓 겠 습 니 다.
activity_lookstaff.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >
   <TextView
    android:id="@+id/tv_title"
    style="@style/GTextView"
    android:text="    " />
  <com.rjxy.view.DeleteListView
    android:id="@+id/id_listview"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:layout_below="@+id/tv_title">
  </com.rjxy.view.DeleteListView>
</RelativeLayout>
delete_btn.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:orientation="vertical" >
   <Button 
    android:id="@+id/id_item_btn"
    android:layout_width="60dp"
    android:singleLine="true"
    android:layout_height="wrap_content"
    android:text="  "
     android:background="@drawable/d_delete_btn"
     android:textColor="#ffffff"
     android:paddingLeft="15dp"
     android:paddingRight="15dp"
     android:layout_alignParentRight="true"
     android:layout_centerVertical="true"
     android:layout_marginRight="15dp"
    />
</LinearLayout>
d_delete_btn.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/btn_style_five_focused" android:state_focused="true"></item>
  <item android:drawable="@drawable/btn_style_five_pressed" android:state_pressed="true"></item>
  <item android:drawable="@drawable/btn_style_five_normal"></item>
</selector>
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;
  /**
   *       x  
   */
  private int xDown;
  /**
   *       y  
   */
  private int yDown;
  /**
   *       x  
   */
  private int xMove;
  /**
   *       y  
   */
  private int yMove;
  private LayoutInflater mInflater;
  private PopupWindow mPopupWindow;
  private int mPopupWindowHeight;
  private int mPopupWindowWidth;
  private Button mDelBtn;
  /**
   *              
   */
  private DelButtonClickListener mListener;
  /**
   *        View
   */
  private View mCurrentView;
  /**
   *          
   */
  private int mCurrentViewPos;
  /**
   *         
   * 
   * @param context
   * @param attrs
   */
  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);
    /**
     *     measure,        
     */
    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;
      /**
       *     popupWindow  ,     ,    ListView touch     
       */
      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);
  }
  /**
   *   popupWindow
   */
  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<String> mAdapter;
  private List<String> staffs = new ArrayList<String>();
  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() + "
:" + staff.getSname() + "
:" + staff.getDname()); } mAdapter = new ArrayAdapter<String>( 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("
"); 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(); } }
위 에서 말 한 것 은 소 편 이 소개 한 안 드 로 이 드 슬라이딩 삭제 데이터 기능 의 실현 코드 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 면 메 시 지 를 남 겨 주세요.소 편 은 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기