本文主要是介绍侧滑删除进阶(一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
效果是在某个Item上右滑可以删除某个条目--效果虽然很简单,但是思路很重要
MainActivity
package com.yangfuhai.animation1;import java.util.ArrayList;import android.app.ListActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;public class MainActivity extends ListActivity {private ArrayList<String> array;private ArrayAdapter<String> adapter;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);ListView listView = getListView();array = new ArrayList<String>();String aa[] = { "items1", "item2", "items3", "item4", "items5","item6", "items7", "item8", "items9", "item10", "items11","item12" };for (int i = 0; i < aa.length; i++) {array.add(aa[i]);}adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array);listView.setAdapter(adapter);listView.setOnTouchListener(new OnTouchListener() {float x, y, upx, upy;public boolean onTouch(View view, MotionEvent event) {if (event.getAction() == MotionEvent.ACTION_DOWN) {Toast.makeText(MainActivity.this, "down", 0).show();x = event.getX();y = event.getY();}if (event.getAction() == MotionEvent.ACTION_UP) {Toast.makeText(MainActivity.this, "up", 0).show();upx = event.getX();upy = event.getY();// 我把它理解为通过x和y的位置来确定这个listView里面这个item的位置int position1 = ((ListView) view).pointToPosition((int) x,(int) y);int position2 = ((ListView) view).pointToPosition((int) upx, (int) upy);if (position1 == position2 && upx > x&& Math.abs(x - upx) > 50) {View v = ((ListView) view).getChildAt(position1);removeListItem(v, position1);}}return false;}});listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View rowView,int positon, long id) {Toast.makeText(rowView.getContext(),"你点击了第" + positon + "位置的item", Toast.LENGTH_SHORT).show();}});}protected void removeListItem(View rowView, final int positon) {final Animation animation = (Animation) AnimationUtils.loadAnimation(rowView.getContext(), R.anim.item_anim);animation.setAnimationListener(new AnimationListener() {public void onAnimationStart(Animation animation) {}public void onAnimationRepeat(Animation animation) {}public void onAnimationEnd(Animation animation) {array.remove(positon);adapter.notifyDataSetChanged();animation.cancel();}});rowView.startAnimation(animation);}
}
item_anim.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"android:duration="800"android:fromXDelta="0"android:fromYDelta="0"android:toXDelta="800"android:toYDelta="0" />
这篇关于侧滑删除进阶(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!