Dummynote with slide deletion, slide deletion dummynote

Source: Internet
Author: User
Tags date now

Dummynote with slide deletion, slide deletion dummynote

Introduction: first, this application integrates the Dummynote I made earlier. The note deletion mainly relies on the ContextMenu after the long-pressed

Public void onCreateContextMenu (ContextMenu menu, View v, ContextMenuInfo menuInfo) {menu. add (0, MENU_DELETE, 0, "delete notebook"); menu. setHeaderTitle ("How do I deal with this record? "); Super. onCreateContextMenu (menu, v, menuInfo );}

This is not bad. However, if you can achieve sliding deletion, the effect will be better. So I drew on this article http://blog.csdn.net/xiaanming/article/details/18311877

The article is very detailed and has many comments. He tells you how to implement sliding deletion step by step.



Difficulties:

Question 1: when a user wants to delete a row, I can only get the row number of the row, but I don't know what the value of _ id is in the database?

Therefore, I used statements with limit and offest.

Set

db.delete(DATABASE_TABLE,ROWID+"="+rowId,null);
Changed

Db.exe cSQL ("delete from tids where _ id in (select _ id from tids limit 1 offset" + rowId + ");"); // query a data entry starting from the rowId + 1 data entry in the database, that is, the rouId + 1

Knowledge:

Top 10 rows

select user_id from udb_user  limit 10; 

Skip the first 10 rows and then extract the first 15 rows.

select user_id from udb_user  limit 10,15; 
Skip the first 15 rows and then extract the first 10 rows.

select user_id from udb_user  limit 10 offest 15; 





Not to mention, the code is provided.

Healthyids

Package demo. xpf. healthytids; import android. content. intent; import android. OS. bundle; import android. app. activity; import android. content. intent; import android. database. cursor; import android. support. v4.widget. simpleCursorAdapter; import android. text. staticLayout; import android. util. log; import android. view. menu; import android. view. menuItem; import android. view. view; import android. widget. adapterView; impor T android. widget. toast; import android. widget. adapterView. onItemClickListener; import demo. xpf. healthytids. swipeDismissListView. onDismissCallback; public class Healthytids extends Activity {private static final String TAG = "tids"; private SwipeDismissListView swipeDismissListView; @ Overrideprotected void onCreate (Bundle savedInstanceState. onCreate (savedInstanceState); setContentView (R. layout. ma In); // getListView (). setEmptyView (findViewById (R. id. empty); // when the list is empty, the display content is empty text box setAdapter (); init ();} private TidsDbAdapter mDbHelper; private Cursor mTidCursor; private void setAdapter () {mDbHelper = new TidsDbAdapter (this); mDbHelper. open (); fillData () ;}// fillData () refresh data private void fillData () {mTidCursor = mDbHelper. getall (); Log. d (TAG, "filldata" + mTidCursor); startManagingCursor (mTidCursor); String [] From = new String [] {TidsDbAdapter. NOTE}; int [] to = new int [] {android. r. id. text1}; // android. r. id. text1 is an identifier of TextView In the Android framework. // Now create a simple cursor adapterSimpleCursorAdapter adapter = new SimpleCursorAdapter (this, android. r. layout. simple_list_item_1, mTidCursor, from, to); swipeDismissListView = (SwipeDismissListView) findViewById (R. id. swipeDismissListView); swipeDismissListView. setAdapt Er (adapter);} private void init () {swipeDismissListView. setOnDismissCallback (new OnDismissCallback () {@ Overridepublic void onDismiss (int dismissPosition) {// adapter. remove (adapter. getItem (dismissPosition); boolean T = mDbHelper. delete (dismissPosition); Log. d (TAG, "delete" + dismissPosition + "" + T); fillData () ;}}); swipeDismissListView. setOnItemClickListener (new OnItemClickListener () {private static final Int ACTIVITY_EDIT = 0x1001; public void onItemClick (AdapterView <?> Parent, View view, int position, long id) {Intent intent = new Intent (Healthytids. this, NoteEdit. class); intent. putExtra (TidsDbAdapter. ROWID, id); // id is the _ id value, not the current list item value. Represents the "row ID" startActivityForResult (intent, ACTIVITY_EDIT) ;}}// Add an entityprotected static final int MENU_INSERT = Menu. FIRST; @ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. super. onCreateOptionsMenu (menu); menu. add (0, MENU_INSERT, 0, "add note"); return super. onCreateOptionsMenu (menu);} public boolean onOptionsItemSelected (MenuItem item) {switch (item. getItemId () {case MENU_INSERT: String noteName = "New Note"; mDbHelper. create (noteName); fillData (); return true;} return super. onOptionsItemSelected (item );}}



SwipeDismissListView

Package demo. xpf. healthytids; import static com. nineoldandroids. view. viewHelper. setAlpha; import static com. nineoldandroids. view. viewHelper. setTranslationX; import android. content. context; import android. util. attributeSet; import android. view. motionEvent; import android. view. velocityTracker; import android. view. view; import android. view. viewConfiguration; import android. view. viewGroup; import android. widget. AdapterView; import android. widget. listView; import com. nineoldandroids. animation. animator; import com. nineoldandroids. animation. animatorListenerAdapter; import com. nineoldandroids. animation. valueAnimator; import com. nineoldandroids. view. viewHelper; import com. nineoldandroids. view. viewPropertyAnimator;/*** @ blog http://blog.csdn.net/xiaanming *** @ author xiaanming ***/@ SuppressWarnings ("unused") public Class SwipeDismissListView extends ListView {/*** considers it as the minimum sliding distance */private int mSlop;/*** minimum Sliding Speed */private int mMinFlingVelocity; /*** maximum Sliding Speed */private int mMaxFlingVelocity;/***** animation execution time */protected long mAnimationTime = 150; /*** indicates whether the user is sliding */private boolean mSwiping;/*** sliding speed detection class */private VelocityTracker mVelocityTracker; /*** position pressed by the finger */private int mDownPosition;/*** View corresponding to the item pressed */Private View mDownView; private float mDownX; private float mDownY;/*** item width */private int mViewWidth; /*** when the ListView Item slides out of the interface callback interface */private OnDismissCallback onDismissCallback;/***** set the animation time ** @ param mAnimationTime */public void setmAnimationTime (long mAnimationTime) {this. mAnimationTime = mAnimationTime;}/*** set the deletion callback interface ** @ param onDismissCallback */public void setOnDismissCallback (OnDismi SsCallback onDismissCallback) {this. onDismissCallback = onDismissCallback;} public SwipeDismissListView (Context context) {this (context, null);} public SwipeDismissListView (Context context, AttributeSet attrs) {this (context, attrs, 0 );} public SwipeDismissListView (Context context, AttributeSet attrs, int defStyle) {super (context, attrs, defStyle); ViewConfiguration vc = ViewConfiguration. get (context); MS Lop = vc. getScaledTouchSlop (); mMinFlingVelocity = vc. getScaledMinimumFlingVelocity () * 8; // get the minimum sliding speed. mMaxFlingVelocity = vc. getScaledMaximumFlingVelocity (); // get the maximum Sliding Speed} @ Overridepublic boolean onTouchEvent (MotionEvent ev) {switch (ev. getAction () {case MotionEvent. ACTION_DOWN: handleActionDown (ev); break; case MotionEvent. ACTION_MOVE: return handleActionMove (ev); case MotionEvent. ACTION_UP: handleAction Up (ev); break;} return super. onTouchEvent (ev);}/*** press event processing ** @ param ev * @ return */private void handleActionDown (MotionEvent ev) {mDownX = ev. getX (); mDownY = ev. getY (); mDownPosition = pointToPosition (int) mDownX, (int) mDownY); if (mDownPosition = AdapterView. INVALID_POSITION) {return;} mDownView = getChildAt (mDownPosition-getFirstVisiblePosition (); if (mDownView! = Null) {mViewWidth = mDownView. getWidth ();} // Add speed detection mVelocityTracker = VelocityTracker. obtain (); mVelocityTracker. addMovement (ev);}/*** method for processing finger sliding ** @ param ev * @ return */private boolean handleActionMove (MotionEvent ev) {if (mVelocityTracker = null | mDownView = null) {return super. onTouchEvent (ev);} // obtains the float deltaX = ev distance from X. getX ()-mDownX; float deltaY = ev. getY ()-mDownY; // The sliding distance in the X direction is greater than mS. If (Math. abs (deltaX)> mSlop & Math. abs (deltaY) <mSlop) {mSwiping = true; // when the finger slides the item, the Click Event of the item is canceled, otherwise, we will slide the Item along with the occurrence of the item Click Event MotionEvent cancelEvent = MotionEvent. obtain (ev); cancelEvent. setAction (MotionEvent. ACTION_CANCEL | (ev. getActionIndex () <MotionEvent. ACTION_POINTER_INDEX_SHIFT); onTouchEvent (cancelEvent);} if (mSwiping) {// with whom the finger moves itemViewHelper. setTranslationX (mD OwnView, deltaX); // transparency gradient ViewHelper. setAlpha (mDownView, Math. max (0f, Math. min (1f, 1f-2f * Math. abs (deltaX)/mViewWidth); // when the finger slides, true is returned, indicating that SwipeDismissListView processes onTouchEvent by itself, and the others are handed over to the parent class to process return true ;} return super. onTouchEvent (ev);}/*** handle events raised by fingers * @ param ev */private void handleActionUp (MotionEvent ev) {if (mVelocityTracker = null | mDownView = null |! MSwiping) {return;} float deltaX = ev. getX ()-mDownX; // calculates the speed of X and Y based on the sliding distance. computeCurrentVelocity (1000); float velocityX = Math. abs (mVelocityTracker. getXVelocity (); float velocityY = Math. abs (mVelocityTracker. getYVelocity (); boolean dismiss = false; // whether the item needs to slide out of the screen boolean dismissRight = false; // whether to delete it to the right // if the distance between the dragged item is greater than half of the item, item slides out of the screen if (Math. abs (deltaX)> mViewWidth/2) {dismiss = true; d IsmissRight = deltaX> 0; // the speed at which the finger slides on the screen is within a certain range, also enables the item to slide out of the screen} else if (mMinFlingVelocity <= velocityX & velocityX <= mMaxFlingVelocity & velocityY <velocityX) {dismiss = true; dismissRight = mvelocity. getXVelocity ()> 0;} if (dismiss) {ViewPropertyAnimator. animate (mDownView ). translationX (dismissRight? MViewWidth:-mViewWidth) // The moving distance from the X axis. alpha (0 ). setDuration (mAnimationTime ). setListener (new AnimatorListenerAdapter () {@ Overridepublic void onAnimationEnd (Animator animation) {// Delete javasmdismiss (mDownView, mDownPosition) after the Item slides out of the interface );}});} else {// slide the item to the start position of ViewPropertyAnimator. animate (mDownView ). translationX (0 ). alpha (1 ). setDuration (mAnimationTime ). setListener (null);} // if (mVelocityTracker! = Null) {mVelocityTracker. recycle (); mVelocityTracker = null;} mSwiping = false;}/*** after the item is deleted in this method, the other items scroll up or down, and call back position to method onDismiss () * @ param dismissView * @ param dismissPosition */private void descrimdismiss (final View dismissView, final int dismissPosition) {final ViewGroup. layoutParams lp = dismissView. getLayoutParams (); // get the layout parameter final int originalHeight = dismissView of the item. getHeight (); // The height of the item ValueAnimator animator = ValueAnimator. ofInt (originalHeight, 0 ). setDuration (mAnimationTime); animator. start (); animator. addListener (new AnimatorListenerAdapter () {@ Overridepublic void onAnimationEnd (Animator animation) {if (onDismissCallback! = Null) {onDismissCallback. onDismiss (dismissPosition);} // This code is very important, because we have not removed the item from the ListView, the height of the item is set to 0 // so we will set the item back to ViewHelper after the animation is executed. setAlpha (dismissView, 1f); ViewHelper. setTranslationX (dismissView, 0); ViewGroup. layoutParams lp = dismissView. getLayoutParams (); lp. height = originalHeight; dismissView. setLayoutParams (lp) ;}}); animator. addUpdateListener (new ValueAnimator. animatorUpdateListener () {@ Overridepublic void onAnimationUpdate (ValueAnimator valueAnimator) {// the effect of this Code is that after ListView deletes an item, the effects of moving other items upward are lp. height = (Integer) valueAnimator. getAnimatedValue (); dismissView. setLayoutParams (lp) ;}}) ;}/ *** Delete callback interface ** @ author xiaanming **/public interface OnDismissCallback {public void onDismiss (int dismissPosition );}}


TidsDbAdapter

Package demo. xpf. healthytids; import java. util. date; import android. content. contentValues; import android. content. context; import android. database. SQLException; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteOpenHelper; import android. database. *; import android. util. log; public class TidsDbAdapter {private static final String TAG = "tids"; private static final String DATA BASE_NAME = "tids. db "; private static final int DATABASE_VERSION = 1; private static final String DATABASE_TABLE =" tids "; private static final String DATABASE_CREATE = "create table tids (" + "_ id integer primary key," + "note text not null," + "created INTEGER" + ");"; private static class DatabaseHelper extends SQLiteOpenHelper {public DatabaseHelper (Context context) {super (context, DATABASE_NAME, null, DATAB ASE_VERSION); // TODO Auto-generated constructor stub} @ Override // create a data table public void onCreate (SQLiteDatabase db) {// TODO Auto-generated method stubtry mongodb.exe cSQL (DATABASE_CREATE ); log. d (TAG, "onCreate! ");} Catch (Exception e) {Log. d (TAG, e. toString () ;}@ Override // update the public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) data table) {try {// TODO Auto-generated method stubdb.exe cSQL ("drop table if exists" + DATABASE_TABLE); onCreate (db); Log. d (TAG, "inUpgrade! ");} Catch (Exception e) {Log. d (TAG," onUpgrade failure! ") ;}} Private Context mCtx = null; // abstract interface private DatabaseHelper dbHelper; // database tool class private SQLiteDatabase db; // Database Class/** COnstructor **/public TidsDbAdapter (Context ctx) {this. mCtx = ctx;} public TidsDbAdapter open () throws SQLException {dbHelper = new DatabaseHelper (mCtx); db = dbHelper. getWritableDatabase (); // if the database does not exist, create one. If the database does exist, decide whether to update the database return this;} public void close () {dbHelper. close ();} public static Final String ROWID = "_ id"; public static final String NOTE = "note"; public static final String CREATED = "created"; // query single entrypublic Cursor get (long rowId) throws SQLException {Cursor mCursor = db. query (DATABASE_TABLE, // Which table to selectnew String [] {ROWID, NOTE, CREATED}, // Which columns to returnROWID + "=" + rowId, // Where clausenull, // Where argumentsnull, // Group By clausenull, // Having c Lausenull // Order-by clause); if (mCursor! = Null) {mCursor. moveToFirst (); // pointer to start} return mCursor;} // query single entrypublic Cursor getall () {return db. query (DATABASE_TABLE, // Which table to selectnew String [] {ROWID, NOTE, CREATED}, // Which columns to returnnull, // Where clausenull, // Where argumentsnull, // Group By clausenull, // Having clausenull // Order-by clause);} // add an entitypublic long create (String Note) {Date now = new Date (); ContentVa Lues args = new ContentValues (); args. put (NOTE, Note); args. put (CREATED, now. getDate (); return db. insert (DATABASE_TABLE, null, args);} // remove an entitypublic boolean delete (long rowId) {Log. d (TAG, "delete func" + rowId); db.exe cSQL ("delete from tids where _ id in (select _ id from tids limit 1 offset" + rowId + "); "); // query a data entry starting from the rowId + 1 data entry in the database, that is, the rouId + 1 data entry. Return true; // return db. delete (DATABASE_TABLE, ROWID + "=" + rowId, null)> 0; // If delete fails, 0 is returned. // update an entitypublic boolean update (long rowId, String note) {ContentValues args = new ContentValues (); args. put (NOTE, note); return db. update (DATABASE_TABLE, args, ROWID + "=" + rowId, null)> 0 ;}}


NoteEdit

Package demo. xpf. healthytids; import android. app. activity; import android. database. cursor; import android. database. sqlite. SQLiteDatabase; import android. OS. bundle; import android. util. log; import android. view. view; import android. widget. button; import android. widget. editText; import demo. xpf. healthytids. tidsDbAdapter; public class NoteEdit extends Activity {private static final String TAG = "tids"; private Tid SDbAdapter mDbHelper; private SQLiteDatabase db; @ Overrideprotected void onCreate (Bundle SavedInstanceState) {super. onCreate (SavedInstanceState); mDbHelper = new TidsDbAdapter (this); mDbHelper. open (); setContentView (R. layout. note_edit); Log. d (TAG, "edit"); findViews (); showViews (SavedInstanceState);} private EditText field_note; private Button button_confirm; private void findViews () {// TODO Auto-generated m Ethod stubfield_note = (EditText) findViewById (R. id. note); button_confirm = (Button) findViewById (R. id. confirm);} private Long mRowId; private void showViews (Bundle savedInstanceState) {mRowId = savedInstanceState! = Null? SavedInstanceState. getLong (TidsDbAdapter. ROWID): null;/* in the "bundle" Data container of "saveInstanceState", the last time the Activity is in the "stop" status, the key value is "_ id" (NotesDbAdapter. ROWID. If the ACtivity is newly opened or the previous itinerary has been recycled, the value of "mRouId" is set to "null" */if (mRowId = null) {Bundle extras = getIntent (). getExtras (); mRowId = extras! = Null? Extras. getLong (TidsDbAdapter. ROWID): null; Log. d (TAG, "position" + mRowId);/* Cursor mCursor = db. query ("tids", new String [] {"_ id"}, null, mRowId + "1"); while (mCursor! = Null) {mRowId = mCursor. getLong (0); // obtain the value of the first column. The index of the first column starts from 0. d (TAG, "id" + mRowId);} */} populateFields (); // query records based on RowId and display in EditText the button_confirm.setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {mDbHelper. update (mRowId, field_note.getText (). toString (); setResult (RESULT_ OK); finish () ;}});} private void populateFields () {if (mRowId! = Null) {Cursor note = mDbHelper. get (mRowId); startManagingCursor (note); field_note.setText (note. getString (note. getColumnIndexOrThrow (TidsDbAdapter. NOTE )));}}}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.