侧滑删除SwipeLayout

发布于 2018-03-23  20 次阅读


最近在外包项目中使用到了SwipeLayout,稍微学习了下,其中也有不少细节需要注意。所以将代码记录下来,以便以后参考。

主要有三个地方需要写。

首先是布局文件,使用com.daimajia.swipe.SwipeLayout,其中放置两个LinearLayout,第一个为位于底部侧滑后显示的布局,第二个为在上面侧滑前的布局。

定义Adapter,继承BaseSwipeAdapter,注意数据和监听器在fillValues中设置,不要在generateView中使用。

最后使用时,对listview使用setAdapter即可。

样例

布局

<?xml version="1.0" encoding="utf-8" ?>
<com.daimajia.swipe.SwipeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:swipe="http://schemas.android.com/apk/res-auto"
    android:id="@+id/user_swipe"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    swipe:leftEdgeSwipeOffset="0dp"
    swipe:rightEdgeSwipeOffset="0dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:background="#FF5534"
        android:gravity="center"
        android:tag="Bottom3"
        android:weightSum="10">

        <ImageView
            android:layout_width="27dp"
            android:layout_height="30dp"
            android:layout_weight="1"
            android:src="@drawable/delete" />

        <TextView
            android:layout_width="0dp"
            android:id="@+id/user_password"
            android:layout_height="wrap_content"
            android:layout_weight="5"
            android:text=""
            android:textColor="#fff"
            android:textSize="17sp" />

        <Button
            android:id="@+id/delete"
            android:layout_width="0dp"
            android:layout_height="40dp"
            android:layout_weight="4"
            android:background="@drawable/white"
            android:text="删除用户"
            android:textColor="#FF5534" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:id="@+id/user_username"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/user_name"
            android:layout_width="match_parent"
            android:textStyle="bold"
            android:layout_weight="1"
            android:layout_height="wrap_content" />

    </LinearLayout>
</com.daimajia.swipe.SwipeLayout>

Adapter

package cn.likole.bookmanager.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.daimajia.swipe.SimpleSwipeListener;
import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.BaseSwipeAdapter;

import java.io.IOException;
import java.util.List;

import cn.likole.bookmanager.R;
import cn.likole.bookmanager.bean.UserBean;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static cn.likole.bookmanager.Constant.basic_url;

/**
 * Created by likole on 3/23/18.
 */

public class UserAdapter extends BaseSwipeAdapter {

    private Context mContext;
    private List<UserBean> mDatas;
    //private TextView mDelete;
    //private SwipeLayout swipeLayout;
    private int pos;

    public UserAdapter(Context context, List<UserBean> mDatas) {
        this.mContext = context;
        this.mDatas = mDatas;
    }

    public void update(List<UserBean> mDatas) {
        this.mDatas = mDatas;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return mDatas.get(position);
    }

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

    @Override
    public void fillValues(final int position, View convertView) {
        Log.e("fillValues", "position = " + position);
        TextView tv = (TextView) convertView.findViewById(R.id.user_username);
        //tv.setText((position + 1) + ".");
        tv.setText("账号:" + mDatas.get(position).getUserUsername() + "(用户编号:" + mDatas.get(position).getUserId() + ")");
        TextView tv2 = (TextView) convertView.findViewById(R.id.user_name);
        tv2.setText("用户名:" + mDatas.get(position).getUserName() + (mDatas.get(position).getUserPower() == 1 ? "(管理员)" : ""));
        TextView tv3 = (TextView) convertView.findViewById(R.id.user_password);
        tv3.setText("密码:" + mDatas.get(position).getUserPassword());

        final SwipeLayout sl = (SwipeLayout) convertView.findViewById(getSwipeLayoutResourceId(position));
        final TextView delete = (TextView) convertView.findViewById(R.id.delete);
        delete.setTag(position);
        delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //发送请求
                OkHttpClient client = new OkHttpClient();
                FormBody.Builder formBody = new FormBody.Builder();
                formBody.add("userId", mDatas.get(position).getUserId() + "");
                Request request = new Request.Builder()
                        .url(basic_url + "user/delete")
                        .post(formBody.build())
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                    }
                });

                //删除元素
                int pos = (Integer) delete.getTag();
                UserBean obj = mDatas.get(pos);

                Log.e("onClick", "........pos ...." + pos + " obj = " + obj);
                mDatas.remove(obj);

                //通知更改
                notifyDataSetChanged();
                sl.close();
            }
        });

    }

    @Override
    public View generateView(int position, ViewGroup arg1) {
        Log.e("generateView", "position = " + position);
        View v = LayoutInflater.from(mContext).inflate(R.layout.fragment_user_list_item, null);
        pos = position;
        final SwipeLayout swipeLayout = (SwipeLayout) v.findViewById(R.id.user_swipe);

        swipeLayout.addSwipeListener(new SimpleSwipeListener() {
            @Override
            public void onOpen(SwipeLayout layout) {//当隐藏的删除menu被打开的时候的回调函数
            }
        });

        swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
            @Override
            public void onDoubleClick(SwipeLayout layout,
                                      boolean surface) {
                Toast.makeText(mContext, "DoubleClick", Toast.LENGTH_SHORT).show();

            }
        });
//      v.findViewById(R.id.delete).setOnClickListener(
//              new View.OnClickListener() {
//                  @Override
//                  public void onClick(View view) {
//                      Toast.makeText(mContext, "click delete position = "+pos,Toast.LENGTH_SHORT).show();
//                      swipeLayout.close();
//                  }
//              });

        return v;
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.user_swipe;
    }

}

Fragment/Activity

package cn.likole.bookmanager.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.daimajia.swipe.SwipeLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.likole.bookmanager.R;
import cn.likole.bookmanager.activity.UserAddActivity;
import cn.likole.bookmanager.adapter.UserAdapter;
import cn.likole.bookmanager.bean.UserBean;
import cn.likole.bookmanager.util.SnackBarUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static cn.likole.bookmanager.Constant.basic_url;

public class UserFragment extends BaseFragment {


    private boolean isGetData = false;
    private ListView mListView;
    private Button btn;
    ArrayList<UserBean> list;
    UserAdapter userAdapter;
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    userAdapter.update(list);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void setUpView() {
        mListView = $(R.id.user_list);
        btn = $(R.id.btn_user_addActivity);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), UserAddActivity.class));
            }
        });
    }

    @Override
    protected void setUpData() {
        /**
         * The following comment is the sample usage of ArraySwipeAdapter.
         */
//        UserBean userbean = new UserBean();
//        userbean.setUserId(1000);
//        userbean.setUserUsername("测试用户");
//        userbean.setUserName("正在加载中,请稍候");
//        list.add(userbean);

        list = new ArrayList<>();

        userAdapter = new UserAdapter(getActivity(), list);
        mListView.setAdapter(userAdapter);
        update();

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ((SwipeLayout) (mListView.getChildAt(position - mListView.getFirstVisiblePosition()))).open(true);
            }
        });
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.e("ListView", "OnTouch");
                return false;
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                SnackBarUtils.makeShort(mListView, "滑动删除用户,暂不支持修改,可先删除再添加").success();
//                Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                Log.e("ListView", "onScrollStateChanged");
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

        mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.e("ListView", "onItemSelected:" + position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Log.e("ListView", "onNothingSelected:");
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected int setLayoutResourceID() {
        return R.layout.fragment_user_list;
    }

    public void update() {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder formBody = new FormBody.Builder();
        Request request = new Request.Builder()
                .url(basic_url + "user/userList")
                .post(formBody.build())
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                SnackBarUtils.makeLong(mListView, "网络错误,请检查网络后重试").danger();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    list = new Gson().fromJson(response.body().string(), new TypeToken<List<UserBean>>() {
                    }.getType());
//                    Log.e("info",list.toString());
                    Message msg = new Message();
                    msg.what = 0;
                    handler.sendMessage(msg);
                } catch (Exception e) {
                    //应该不会发生
                }

            }
        });
    }

    //数据更新问题
    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        //   进入当前Fragment
        if (enter && !isGetData) {
            isGetData = true;
            update();
        } else {
            isGetData = false;
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isGetData) {
            update();
            isGetData = true;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isGetData = false;
    }

}