Override listview, slide horizontally to display the delete button, click the button to delete item, listviewitem

Source: Internet
Author: User

Override listview, slide horizontally to display the delete button, click the button to delete item, listviewitem

First, let's take a look:

Next, let's take a look at the specific operations:

Prepare a deletion button layout and create a button. xml file. The Code is as follows:

<?xml version="1.0" encoding="utf-8"?>    <Button  xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/btn"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="delete"/>

This layout is very simple. There is only one button.

Create MyLIstView to inherit from ListView. This is our custom View. The Code is as follows:

Package com. example. animal; import android. content. context; import android. util. attributeSet; import android. view. gestureDetector; import android. view. gestureDetector. onGestureListener; import android. view. layoutInflater; import android. view. motionEvent; import android. view. view; import android. view. view. onTouchListener; import android. view. viewGroup; import android. widget. listView; import android. widget. rela TiveLayout; public class MyListView extends ListView implements OnGestureListener, whether the OnTouchListener {/*** delete button is displayed. The default value is false */boolean isDeleteShow = false; /*** the item clicked */int itemPosition;/*** delete button View */View deleteButton; /*** the entire row view of the clicked item */ViewGroup itemLayout;/*** response OnGestureListener Method */GestureDetector detector; /*** custom Delete listener */onDeleteListener deleteListener; public MyListView (Context co Ntext, AttributeSet attrs) {super (context, attrs); detector = new GestureDetector (getContext (), this); setOnTouchListener (this) ;}@ Overridepublic boolean onTouch (View v, motionEvent event) {if (isDeleteShow) {// itemLayout is displayed if the delete button is displayed. removeView (deleteButton); deleteButton = null; isDeleteShow = false; return false;} else {// return detector if the delete button is not displayed. onTouchEvent (event) ;}@overridepublic boolean onDown (M OtionEvent e) {if (isDeleteShow) {// if the delete button is displayed} else {// if the delete button is not displayed, itemPosition = pointToPosition (int) e. getX (), (int) e. getY () ;}return false ;}@ Overridepublic void onShowPress (MotionEvent e) {}@ Overridepublic boolean onSingleTapUp (MotionEvent e) {return false ;} @ Overridepublic boolean onScroll (MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {return false ;}@ Overridepublic void OnLongPress (MotionEvent e) {}@ Overridepublic boolean onFling (MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {// when the delete button is not displayed, and the transverse sliding speed is greater than the vertical sliding speed if (! IsDeleteShow & Math. abs (velocityX)> Math. abs (velocityY) {deleteButton = LayoutInflater. from (getContext ()). inflate (R. layout. button, null); deleteButton. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {itemLayout. removeView (deleteButton); deleteButton = null; isDeleteShow = false; deleteListener. onDelete (itemPosition) ;}}); // Add the delete button dynamically to itemLayout = (ViewGroup) getChildAt (itemPosition-getFirstVisiblePosition (); RelativeLayout. layoutParams params = new RelativeLayout. layoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); params. addRule (RelativeLayout. ALIGN_PARENT_RIGHT); params. addRule (RelativeLayout. CENTER_VERTICAL); itemLayout. addView (deleteButton, params); isDeleteShow = true;} return false;} public void setDeleteListener (onDeleteListener listener) {deleteListener = listener ;} public interface onDeleteListener {void onDelete (int index );}}



Here, a GestureDetector instance is created in the MyListView constructor to listen to gestures, and a touch listener event is registered for MyLIstView. Then, in the onTouch method, determine that if the delete button is displayed, remove it. If it is not displayed, use GestureDetector to process the current gesture.


When you press the finger, the onDown () method of OnGestureListener is called. Here, the pointToPosition () method is used to determine which row of ListView is currently selected. When the finger slides fast, the onFling () method is called. The delete_button.xml layout is loaded here, And the delete button is added to the selected item. Note: We also added a click event to the delete button. When the delete button is clicked, The onDelete () method of onDeleteListener will be called back. The specific delete operation should be processed in the callback method.




Note: deleting an item in the listView is actually deleting a data adapted to the listView.


Reference the self-created MyLIstView in activity_main, as shown below:

<?xml version="1.0" encoding="utf-8"?><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="fill_parent"  android:layout_height="fill_parent">     <com.example.animal.MyListView        android:id="@+id/list"        android:layout_width="match_parent"        android:layout_height="match_parent"></com.example.animal.MyListView></LinearLayout>

In MainActivity, You can reference it.

package com.example.animal;import java.util.ArrayList;import java.util.List;import com.example.animal.MyListView.onDeleteListener;import android.app.Activity;import android.content.Context;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;public class MainActivity extends Activity {MyListView listView;MyAdapter myAdapter;ArrayList<String> arrayList = new ArrayList<String>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initArrayList();listView = (MyListView) findViewById(R.id.list);myAdapter = new MyAdapter(getApplicationContext(), arrayList);listView.setAdapter(myAdapter);listView.setDeleteListener(new onDeleteListener() {@Overridepublic void onDelete(int index) {arrayList.remove(index);myAdapter.notifyDataSetChanged();}});}private void initArrayList() {arrayList.add("Content Item 1");arrayList.add("Content Item 2");arrayList.add("Content Item 3");arrayList.add("Content Item 4");arrayList.add("Content Item 5");arrayList.add("Content Item 6");arrayList.add("Content Item 7");arrayList.add("Content Item 8");arrayList.add("Content Item 9");arrayList.add("Content Item 10");arrayList.add("Content Item 11");arrayList.add("Content Item 12");arrayList.add("Content Item 13");arrayList.add("Content Item 14");arrayList.add("Content Item 15");arrayList.add("Content Item 16");arrayList.add("Content Item 17");arrayList.add("Content Item 18");arrayList.add("Content Item 19");arrayList.add("Content Item 20");}}class MyAdapter extends BaseAdapter {Context context;ArrayList<String> list;public MyAdapter(Context context, ArrayList<String> list) {this.context = context;this.list = list;}@Overridepublic int getCount() {return 10;}@Overridepublic Object getItem(int position) {return null;}@Overridepublic long getItemId(int position) {return 0;}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {View view;if (convertView == null) {view = LayoutInflater.from(context).inflate(R.layout.textv, null);} else {view = convertView;}TextView tv = (TextView) view.findViewById(R.id.text);tv.setText(list.get(position));return view;}}


The content in MainActivity is very simple and I will not explain it any more.
The small view in listView is as follows:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"     >    <TextView android:id="@+id/text"    android:layout_width="wrap_content"    android:layout_height="100dp"    /></RelativeLayout>


The demo ends.

Reprinted please indicate the source: http://blog.csdn.net/harryweasley/article/details/46224847

For OnGestureListener and OnTouchListener, you can click to view http://blog.csdn.net/harryweasley/article/details/45968923

Reference: http://blog.csdn.net/guolin_blog/article/details/17357967



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.