1. 程式人生 > >Android中RecyclerView的item中控制元件的點選事件新增刪除一行、上移下移一行的程式碼實現

Android中RecyclerView的item中控制元件的點選事件新增刪除一行、上移下移一行的程式碼實現

Demo展示圖片

這裡寫圖片描述

佈局程式碼

// (layout)activity_main.xml
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context
="com.text.recyclerviewdemo.MainActivity">
<android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="wrap_content" android:overScrollMode="never" android:scrollbars="none"/> </RelativeLayout
>
---------------------------------------------------------------------------------------- // (layout)recyclerview_item.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background
="@drawable/recyclerview_bg">
<TextView android:id="@+id/num" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:layout_margin="10dp" android:textColor="#fff"/> <TextView android:id="@+id/data" android:layout_toLeftOf="@+id/ll" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:layout_marginRight="50dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20sp" android:textColor="@color/colorPrimaryDark"/> <LinearLayout android:id="@+id/ll" android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="新增" android:textSize="20sp" android:layout_margin="10dp" android:background="@drawable/ripple_bg" android:clickable="true" android:textColor="#fff"/> <TextView android:id="@+id/del" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="刪除" android:textSize="20sp" android:layout_margin="10dp" android:background="@drawable/ripple_bg" android:clickable="true" android:textColor="#fff"/> <TextView android:id="@+id/up" android:layout_width="35dp" android:layout_height="wrap_content" android:text="↑" android:textSize="20sp" android:gravity="center" android:layout_margin="10dp" android:background="@drawable/ripple_bg" android:clickable="true" android:textColor="#fff"/> <TextView android:id="@+id/down" android:layout_width="35dp" android:layout_height="wrap_content" android:text="↓" android:textSize="20sp" android:gravity="center" android:layout_margin="10dp" android:background="@drawable/ripple_bg" android:clickable="true" android:textColor="#fff"/> </LinearLayout> </RelativeLayout> ---------------------------------------------------------------------------------------- // (layout)recyclerview_bg.xml <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <solid android:color="@color/colorAccent"/> <stroke android:width="1dp" android:color="@color/colorPrimaryDark"/> </shape> </item> </selector> ---------------------------------------------------------------------------------------- // (layout)ripple_bg.xml <ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/colorPrimaryDark"> </ripple>

邏輯程式碼

  注:需在module中的dependencies節點下新增:

compile 'com.yanzhenjie:recyclerview-swipe:1.0.4'
// MyAdapter 
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuAdapter;
import java.util.List;

public class MyAdapter extends SwipeMenuAdapter<MyAdapter.MyViewHolder> {
    private List<String> strList;
    private OnItemClickListener mOnItemClickListener;

    public MyAdapter(List<String> strList){
        this.strList = strList;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.mOnItemClickListener = onItemClickListener;
    }

    @Override
    public View onCreateContentView(ViewGroup parent, int viewType) {
        return LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
    }

    @Override
    public MyAdapter.MyViewHolder onCompatCreateViewHolder(View realContentView, int viewType) {
        MyViewHolder myViewHolder = new MyViewHolder(realContentView);
        myViewHolder.mOnItemClickListener = mOnItemClickListener;
        return myViewHolder;
    }

    @Override
    public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
        holder.num.setText((position + 1) + "");
        holder.data.setText(strList.get(position));
    }

    @Override
    public int getItemCount() {
        return strList == null ? 0 : strList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        OnItemClickListener mOnItemClickListener;
        TextView num;
        TextView data;
        TextView add;
        TextView del;
        TextView up;
        TextView down;

        public MyViewHolder(View itemView) {
            super(itemView);
            num = (TextView) itemView.findViewById(R.id.num);
            data = (TextView) itemView.findViewById(R.id.data);
            add = (TextView) itemView.findViewById(R.id.add);
            del = (TextView) itemView.findViewById(R.id.del);
            up = (TextView) itemView.findViewById(R.id.up);
            down = (TextView) itemView.findViewById(R.id.down);
            add.setOnClickListener(this);
            del.setOnClickListener(this);
            up.setOnClickListener(this);
            down.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if (mOnItemClickListener != null) {
                mOnItemClickListener.onItemClick(getAdapterPosition() , v);
            }
        }
    }
}
----------------------------------------------------------------------------------------
// OnItemClickListener
import android.view.View;

public interface OnItemClickListener {
    void onItemClick(int position , View v);
}
----------------------------------------------------------------------------------------
// MainActivity
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private RecyclerView mRecyclerView;
    private Context mContext = MainActivity.this;
    private List<String> mStrList;
    private MyAdapter mMyAdapter;
    private int clickTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
    }

    public void initData(){
        mStrList = new ArrayList<>();
        for (int i = 0 ; i < 20 ; i++){
            mStrList.add(i + "");
        }
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mMyAdapter = new MyAdapter(mStrList);
        // 設定item及item中控制元件的點選事件
        mMyAdapter.setOnItemClickListener(onItemClickListener);
        mRecyclerView.setAdapter(mMyAdapter);
    }

    /**
     * Item點選監聽
     */
    private OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(int position , View v) {
            switch (v.getId()){
                case R.id.add:
                    clickTime++;
                    Toast.makeText(mContext, "增:" + position, Toast.LENGTH_SHORT).show();
                    mStrList.add(position+ 1 , "增" + clickTime);
                    mMyAdapter.notifyDataSetChanged();
                    Log.i(TAG , "mStrList:" + mStrList.toString());
                    break;

                case R.id.del:
                    Toast.makeText(mContext, "刪:" + position, Toast.LENGTH_SHORT).show();
                    mStrList.remove(position);
                    mMyAdapter.notifyDataSetChanged();
                    break;

                case R.id.up:
                    if(position == 0){
                        Toast.makeText(mContext, "已經在頂部,無法移動!:" + position, Toast.LENGTH_SHORT).show();
                    }else if(position > 0 && position <= mStrList.size()-1){
                        Toast.makeText(mContext, "上:" + position, Toast.LENGTH_SHORT).show();
                        swap(mStrList , position , position-1);
                        mMyAdapter.notifyDataSetChanged();
                    }
                    break;

                case R.id.down:
                    if(position == mStrList.size()-1){
                        Toast.makeText(mContext, "已經在底部,無法移動!:" + position, Toast.LENGTH_SHORT).show();
                    }else if(position >= 0 && position < mStrList.size()-1){
                        Toast.makeText(mContext, "下:" + position, Toast.LENGTH_SHORT).show();
                        swap(mStrList , position , position+1);
                        mMyAdapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    };

    /**
     * 集合中兩個元素的交換操作
     * @param list
     * @param oldPosition
     * @param newPosition
     * @param <T>
     */
    public static <T> void swap(List<T> list, int oldPosition, int newPosition){
        if(null == list){
            throw new IllegalStateException("The list can not be empty...");
        }
        T tempElement = list.get(oldPosition);

        // 向前移動,前面的元素需要向後移動
        if(oldPosition < newPosition){
            for(int i = oldPosition; i < newPosition; i++){
                list.set(i, list.get(i + 1));
            }
            list.set(newPosition, tempElement);
        }
        // 向後移動,後面的元素需要向前移動
        if(oldPosition > newPosition){
            for(int i = oldPosition; i > newPosition; i--){
                list.set(i, list.get(i - 1));
            }
            list.set(newPosition, tempElement);
        }
    }
}