Android滑動(dòng)刪除數(shù)據(jù)功能的實(shí)現(xiàn)代碼
今天學(xué)習(xí)了新的功能那就是滑動(dòng)刪除數(shù)據(jù)。先看一下效果
我想這個(gè)效果大家都很熟悉吧。是不是在qq上看見(jiàn)過(guò)這個(gè)效果。俗話說(shuō)好記性不如賴筆頭,為了我的以后,為了跟我一樣自學(xué)的小伙伴們,我把我的代碼粘貼在下面。
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"; /** * 用戶滑動(dòng)的最小距離 */ private int touchSlop; /** * 是否響應(yīng)滑動(dòng) */ private boolean isSliding; /** * 手指按下時(shí)的x坐標(biāo) */ private int xDown; /** * 手指按下時(shí)的y坐標(biāo) */ private int yDown; /** * 手指移動(dòng)時(shí)的x坐標(biāo) */ private int xMove; /** * 手指移動(dòng)時(shí)的y坐標(biāo) */ private int yMove; private LayoutInflater mInflater; private PopupWindow mPopupWindow; private int mPopupWindowHeight; private int mPopupWindowWidth; private Button mDelBtn; /** * 為刪除按鈕提供一個(gè)回調(diào)接口 */ private DelButtonClickListener mListener; /** * 當(dāng)前手指觸摸的View */ private View mCurrentView; /** * 當(dāng)前手指觸摸的位置 */ 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); /** * 先調(diào)用下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; /** * 如果當(dāng)前popupWindow顯示,則直接隱藏,然后屏蔽ListView的touch事件的下傳 */ if (mPopupWindow.isShowing()) { dismissPopWindow(); return false; } // 獲得當(dāng)前手指按下時(shí)的item的位置 mCurrentViewPos = pointToPosition(xDown, yDown); // 獲得當(dāng)前手指按下時(shí)的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; /** * 判斷是否是從右到左的滑動(dòng) */ 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(); /** * 如果是從右到左的滑動(dòng)才相應(yīng) */ if (isSliding) { switch (action) { case MotionEvent.ACTION_MOVE: int[] location = new int[2]; // 獲得當(dāng)前item的位置x與y mCurrentView.getLocationOnScreen(location); // 設(shè)置popupWindow的動(dòng)畫 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); // 設(shè)置刪除按鈕的回調(diào) 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; } // 相應(yīng)滑動(dòng)期間屏幕itemClick事件,避免發(fā)生沖突 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; // 主線程創(chuàng)建消息處理器 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("員工號(hào):" + staff.getSno() + "\n姓 名:" + staff.getSname() + "\n部 門:" + 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("\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 { // 區(qū)別1、url的路徑不同 URL url = new URL(Path.lookStaffPath); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); // 區(qū)別2、請(qǐng)求方式post conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Mozilla/5.0(compatible;MSIE 9.0;Windows NT 6.1;Trident/5.0)"); // 區(qū)別3、必須指定兩個(gè)請(qǐng)求的參數(shù) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 請(qǐng)求的類型 表單數(shù)據(jù) String data = ""; conn.setRequestProperty("Content-Length", data.length() + "");// 數(shù)據(jù)的長(zhǎng)度 // 區(qū)別4、記得設(shè)置把數(shù)據(jù)寫給服務(wù)器 conn.setDoOutput(true);// 設(shè)置向服務(wù)器寫數(shù)據(jù) byte[] bytes = data.getBytes(); conn.getOutputStream().write(bytes);// 把數(shù)據(jù)以流的方式寫給服務(wù)器 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 { // 區(qū)別1、url的路徑不同 URL url = new URL(Path.deleteStaffPath); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); // 區(qū)別2、請(qǐng)求方式post conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", "Mozilla/5.0(compatible;MSIE 9.0;Windows NT 6.1;Trident/5.0)"); // 區(qū)別3、必須指定兩個(gè)請(qǐng)求的參數(shù) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 請(qǐng)求的類型 表單數(shù)據(jù) String data = "sno=" + sno; conn.setRequestProperty("Content-Length", data.length() + "");// 數(shù)據(jù)的長(zhǎng)度 // 區(qū)別4、記得設(shè)置把數(shù)據(jù)寫給服務(wù)器 conn.setDoOutput(true);// 設(shè)置向服務(wù)器寫數(shù)據(jù) byte[] bytes = data.getBytes(); conn.getOutputStream().write(bytes);// 把數(shù)據(jù)以流的方式寫給服務(wù)器 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滑動(dòng)刪除數(shù)據(jù)功能的實(shí)現(xiàn)代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Android 3D旋轉(zhuǎn)動(dòng)畫效果實(shí)現(xiàn)分解
如何實(shí)現(xiàn)View的3D旋轉(zhuǎn)效果,實(shí)現(xiàn)的主要原理就是圍繞Y軸旋轉(zhuǎn),同時(shí)在Z軸方面上有一個(gè)深入的縮放,具體實(shí)現(xiàn)代碼如下,感興趣的朋友可以參考下哈2013-06-06EditText監(jiān)聽(tīng)方法,實(shí)時(shí)的判斷輸入多少字符
在EditText提供了一個(gè)方法addTextChangedListener實(shí)現(xiàn)對(duì)輸入文本的監(jiān)控。本文分享了EditText監(jiān)聽(tīng)方法案例,需要的朋友一起來(lái)看下吧2016-12-12Android?Jetpack組件ViewModel基本用法詳解
這篇文章主要為大家介紹了Android?Jetpack組件ViewModel基本用法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01Android采用雙緩沖技術(shù)實(shí)現(xiàn)畫板
這篇文章主要為大家詳細(xì)介紹了Android采用雙緩沖技術(shù)實(shí)現(xiàn)畫板的相關(guān)資料,思路清晰,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05Android編程中出現(xiàn)The connection to adb is down問(wèn)題的解決方法
這篇文章主要介紹了Android編程中出現(xiàn)The connection to adb is down問(wèn)題的解決方法,涉及Android進(jìn)程與服務(wù)的相關(guān)操作技巧,需要的朋友可以參考下2015-12-12Android中通過(guò)RxJava進(jìn)行響應(yīng)式程序設(shè)計(jì)的入門指南
響應(yīng)式編程在Android中的運(yùn)用是非常犀利的,比如在異常處理和調(diào)度器方面,這里我們將從生命周期等方面來(lái)講解Android中通過(guò)RxJava進(jìn)行響應(yīng)式程序設(shè)計(jì)的入門指南:2016-06-06