Android之自定义ListView左滑删除Item效果

Posted 冰糖葫芦三剑客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android之自定义ListView左滑删除Item效果相关的知识,希望对你有一定的参考价值。

1.主函数:

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.tokenloan.lightwallet.R;
import com.tokenloan.lightwallet.common.base.BaseActivity;
import com.tokenloan.lightwallet.utils.ToastUtil;
import com.tokenloan.lightwallet.view.mine.adapter.MessageListAdapter;
import com.tokenloan.lightwallet.widget.ZQListView;

import java.util.ArrayList;
import java.util.List;

import static com.orhanobut.logger.Logger.init;

/**
 * Created by sgf
 */

public class MessageCenterActivity extends BaseActivity implements View.OnClickListener

    private ZQListView lv_message_center;
    private List<String> list = new ArrayList<>();
    private MessageListAdapter messageListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message_center_activity);
        TextView tv_title_order = findViewById(R.id.tv_title_order);
        TextView tv_message_hide_null = findViewById(R.id.tv_message_hide_null);
        lv_message_center = findViewById(R.id.lv_message_center);
        tv_title_order.setText(R.string.msg_center);

        findViewById(R.id.iv_title_back).setOnClickListener(this);
        initView();
    

    private void initView() 
        for (int i = 0; i < 55; i++) 
            list.add("KINGKINGKINGKINGKINGKINGKINGKINGKINGKINGKINGKINGKINGKINGKINGKINGKING" + i);
        
        messageListAdapter = new MessageListAdapter(MessageCenterActivity.this);
        messageListAdapter.setData(list);
        lv_message_center.setAdapter(messageListAdapter);
        lv_message_center.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
                ToastUtil.showShort(MessageCenterActivity.this,"第"+i+"个");
            
        );
    

    @Override
    public void onClick(View view) 
        switch (view.getId()) 
            case R.id.iv_title_back:
                finish();
                break;
            default:
                break;
        
    


2.主函数布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@color/colorWhite"
    android:layout_height="match_parent">

    <include
        android:id="@+id/bolck_titlebar_message"
        layout="@layout/header_home_eth_order" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_below="@+id/bolck_titlebar_message"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_message_hide_null"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:visibility="gone"
            android:text="@string/no_msg"
            android:textColor="@color/gray_seven"
            android:textSize="16sp" />
        <View
            android:layout_width="match_parent"
            android:layout_height="10dp"
            android:background="@color/fengexian_one"></View>
        <com.tokenloan.lightwallet.widget.ZQListView
            android:id="@+id/lv_message_center"
            android:divider="@color/fengexian_one"
            android:dividerHeight="10dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></com.tokenloan.lightwallet.widget.ZQListView>
    </LinearLayout>
</RelativeLayout>

3.适配器:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.tokenloan.lightwallet.R;
import com.tokenloan.lightwallet.view.wallet.bean.Wallet;
import com.tokenloan.lightwallet.widget.ZQView;

import java.util.List;

/**
 * 消息中心适配器
 * Created by sgf
 */

public class MessageListAdapter extends BaseAdapter 

    private Context context;
    private List<String> list;
    private LayoutInflater inflater;


    public MessageListAdapter(Context context) 
        this.context = context;
        inflater = LayoutInflater.from(context);
    

//    public void setData(List<Wallet> arrWallet) 
//        mArrWallet = arrWallet;
//        notifyDataSetChanged();
//    
    public void setData(List<String> lists) 
        list = lists;
        notifyDataSetChanged();
    

    @Override
    public int getCount() 
        if (list == null) 
            return 0;
        
        return list.size();
    

    @Override
    public String getItem(int position) 
        return list.get(position);
    

    @Override
    public long getItemId(int position) 
        return position;
    

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) 

        ViewHolder viewHolder = null;
//        if (convertView == null) 
//            convertView = inflater.inflate(R.layout.message_list_item, null);
//            viewHolder = new ViewHolder();
//            viewHolder.tv_message_item_content = convertView.findViewById(R.id.tv_message_item_content);
//            viewHolder.tv_message_item_time = convertView.findViewById(R.id.tv_message_item_time);
//            convertView.setTag(viewHolder);
//
//         else 
//            viewHolder = (ViewHolder) convertView.getTag();
//        
        ZQView slideView = (ZQView) convertView;
        if (slideView == null) 
            View itemView = inflater.inflate(R.layout.message_list_item, null);

            slideView = new ZQView(context);
            slideView.setContentView(itemView);
            viewHolder = new ViewHolder(slideView);
            slideView.setTag(viewHolder);
         else 
            viewHolder = (ViewHolder) slideView.getTag();
        
        slideView.shrink();//设置删除按钮恢复原来的位置,即消失
        viewHolder.tv_message_item_content.setText(list.get(position));
        viewHolder.deleteHolder.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                list.remove(position);
                notifyDataSetChanged();
            
        );
//        viewHolder.tv_message_item_time.setText(list.get(position));


        return slideView;
    

    static class ViewHolder 
        public TextView tv_message_item_content;
        public TextView tv_message_item_time;
        public ViewGroup deleteHolder;
        ViewHolder(View view) 
            tv_message_item_content = (TextView) view.findViewById(R.id.tv_message_item_content);
            tv_message_item_time = (TextView) view.findViewById(R.id.tv_message_item_time);

            deleteHolder = (ViewGroup) view.findViewById(R.id.holder);
        
    

4.适配器布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_height="match_parent">

        <View
            android:layout_width="match_parent"
            android:layout_height="10dp"
            android:visibility="gone"
            android:background="@color/fengexian_one"></View>
        <RelativeLayout
            android:layout_width="match_parent"
            android:background="@color/colorWhite"
            android:layout_height="116dp">
            <TextView
                android:id="@+id/tv_message_item_time"
                android:layout_width="wrap_content"
                android:layout_marginTop="15dp"
                android:layout_marginLeft="14.5dp"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:text="2018-06-09 12:12"
                android:textColor="@color/black_one"
                android:textSize="13sp" />
            <TextView
                android:id="@+id/tv_message_item_content"
                android:layout_width="match_parent"
                android:layout_marginTop="10dp"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/tv_message_item_time"
                android:layout_marginLeft="15dp"
                android:layout_marginRight="15dp"
                android:layout_height="wrap_content"
                android:text="当前价格========================"
                android:textColor="@color/gray_seven"
                android:textSize="14sp" />
        </RelativeLayout>

    </LinearLayout>


</LinearLayout>

5.自定义ListView类:

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ListView;

/****
 * 
 * 自定义ListView控件
 * 
 * @author sgf
 *
 */
public class ZQListView extends ListView 

	private static final String TAG = "SilderListView";

	private ZQView mFocusedItemView;

	float mX = 0;
	float mY = 0;
	private int mPosition = -1;
	boolean isSlider = false;

	public ZQListView(Context context) 
		super(context);
	

	public ZQListView(Context context, AttributeSet attrs) 
		super(context, attrs);
	

	public ZQListView(Context context, AttributeSet attrs, int defStyle) 
		super(context, attrs, defStyle);
	

	@Override
	public boolean onTouchEvent(MotionEvent event) 
		float x = event.getX();
		float y = event.getY();
		switch (event.getAction()) 
		case MotionEvent.ACTION_DOWN:
			isSlider = false;
			mX = x;
			mY = y;
			int position = pointToPosition((int) x, (int) y);
			if (mPosition != position) 
				mPosition = position;
				if (mFocusedItemView != null) 
					mFocusedItemView.reset();
				
			
			break;
		case MotionEvent.ACTION_MOVE:
			if (mPosition != -1) 
				if (Math.abs(mY - y) < 30 && Math.abs(mX - x) > 20) 
					int first = this.getFirstVisiblePosition();
					int index = mPosition - first;
					mFocusedItemView = (ZQView) getChildAt(index);
					mFocusedItemView.onTouchEvent(event);
					isSlider = true;
					return true;
				
			
			break;
		case MotionEvent.ACTION_UP:
			if (isSlider) 
				isSlider = false;
				if (mFocusedItemView != null) 
					mFocusedItemView.adjust(mX - x > 0);
					return true;
				
			
			break;
		
		return super.onTouchEvent(event);
	

6.自定义侧滑类: 

import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Scroller;

import com.tokenloan.lightwallet.R;

/****
 * 
 *侧滑布局设计
 * 
 * @author sgf
 *
 */
public class ZQView extends LinearLayout 
	private static final String TAG = "SlideView";
	private static final int TAN = 2;
	private int mHolderWidth = 65;
	private float mLastX = 0;
	private float mLastY = 0;
	private Context mContext;
	private LinearLayout mViewContent;
	private Scroller mScroller;

	public ZQView(Context context, Resources resources) 
		super(context);
		initView();
	

	public ZQView(Context context) 
		super(context);
		initView();
	

	public ZQView(Context context, AttributeSet attrs) 
		super(context, attrs);
		initView();
	

	private void initView() 
		setOrientation(LinearLayout.HORIZONTAL);
		mContext = getContext();
		mScroller = new Scroller(mContext);
		View.inflate(mContext, R.layout.delete_view, this);
		mViewContent = (LinearLayout) findViewById(R.id.view_content);
		mHolderWidth = Math.round(TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, mHolderWidth, getResources()
						.getDisplayMetrics()));
	

	public void setContentView(View view) 
		mViewContent.addView(view);
	

	public void shrink() 
		int offset = getScrollX();
		if (offset == 0) 
			return;
		
		scrollTo(0, 0);
	

	public void reset() 
		int offset = getScrollX();
		if (offset == 0) 
			return;
		
		smoothScrollTo(0, 0);
	

	public void adjust(boolean left) 
		int offset = getScrollX();
		if (offset == 0) 
			return;
		
		if (offset < 20) 
			this.smoothScrollTo(0, 0);
		 else if (offset < mHolderWidth - 20) 
			if (left) 
				this.smoothScrollTo(mHolderWidth, 0);
			 else 
				this.smoothScrollTo(0, 0);
			
		 else 
			this.smoothScrollTo(mHolderWidth, 0);
		
	

	@Override
	public boolean onTouchEvent(MotionEvent event) 
		switch (event.getAction()) 
		case MotionEvent.ACTION_MOVE:
			float x = event.getX();
			float y = event.getY();
			float deltaX = x - mLastX;
			float delatY = y - mLastY;
			mLastX = x;
			mLastY = y;
			if (Math.abs(deltaX) < Math.abs(delatY) * TAN) 
				break;
			
			if (deltaX != 0) 
				float newScrollX = getScrollX() - deltaX;
				if (newScrollX < 0) 
					newScrollX = 0;
				 else if (newScrollX > mHolderWidth) 
					newScrollX = mHolderWidth;
				
				this.scrollTo((int) newScrollX, 0);
			
			break;
		
		return super.onTouchEvent(event);
	

	private void smoothScrollTo(int destX, int destY) 
		int scrollX = getScrollX();
		int delta = destX - scrollX;
		mScroller.startScroll(scrollX, 0, delta, 0, Math.abs(delta) * 3);
		invalidate();
	

	@Override
	public void computeScroll() 
		if (mScroller.computeScrollOffset()) 
			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
			postInvalidate();
		
	

7.侧滑布局:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/view_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/holder"
        android:layout_width="65dp"
        android:layout_height="116dp"
        android:clickable="true"
        android:background="@drawable/holder_bg">

        <TextView
            android:id="@+id/delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:textSize="18sp"
            android:textColor="@color/colorWhite"
            android:text="删除" />
        <!--android:drawableLeft="@drawable/del_icon_normal"-->
    </RelativeLayout>

</merge>

 

以上是关于Android之自定义ListView左滑删除Item效果的主要内容,如果未能解决你的问题,请参考以下文章

[Android-2A] -仿IOS微信滑动删除_SwipeListview左滑删除例子

( 转)Android之自定义适配器

android 左滑删除控件,仿ios的左滑

使用swipelistview向左滑动不动

Android自定义组合控件---教你如何自定义下拉刷新和左滑删除

Android自定义组合控件---教你如何自定义下拉刷新和左滑删除