RecyclerView 以及 ItemClickListener的实现

      RecyclerView 的一些基本知识点,可以去官网上查看到。现在这些只是个人的一些笔记而已。

        

    1.Item 位置   ----------  LayoutManager
       Item 分割线 --------- ItemDecoration
       Item 动画效果 ------- ItemAnimator

      2、自定义分割线
          1)、在drawable 中定义已shape为root 的xml文件
          2)、在style中引用
      
      3、Item增加、删除调用的方法
            notifyItemInserted() notifyItemRemove()

      4、Item 的点击事件需要自己定义实现


      具体的实现:
    1、在build.gradle 中增加
       
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    compile 'com.android.support:recyclerview-v7:22.1.1'
}


    2、RecyclerViewActivity

public class RecyclerViewActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private List<String> mStringList;
    private MyRecyclerViewAdapter mRecyclerViewAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view);

        initDates();

        initView();

        mRecyclerViewAdapter = new MyRecyclerViewAdapter(this, mStringList);
        mRecyclerView.setAdapter(mRecyclerViewAdapter);

        // 设置RecyclerView的方向
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayout.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);

        // 设置RecyclerView的分割线
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayout.VERTICAL);
        mRecyclerView.addItemDecoration(dividerItemDecoration);

        // 设置RecyclerView添加或删除的动画
        ScaleInAnimator animator = new ScaleInAnimator();
        mRecyclerView.setItemAnimator(animator);

        // 设置RecyclerView 的点击事件
        mRecyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(RecyclerViewActivity.this, mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Toast.makeText(RecyclerViewActivity.this, "item click position: " + position , Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {
                        Toast.makeText(RecyclerViewActivity.this, "item long click position: " + position , Toast.LENGTH_SHORT).show();
                    }
                })
        );

    }

    // 初始化数据
    private void initDates(){
        mStringList = new ArrayList<>();
        for (int i = 'A'; i  <= 'z'; i ++){
            mStringList.add("" + (char)i);
        }
    }

    // 初始化视图
    private void initView(){
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater  inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_recycler_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_add:
                mRecyclerViewAdapter.add(4);
                return true;

            case R.id.action_deleted:
                mRecyclerViewAdapter.deleted(1);
                return  true;
        }
        return super.onOptionsItemSelected(item);
    }
}

    其中我们的Adapter需要继承RecyclerView的Adapter

2.MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyViewHolder> {

    private Context mContext;
    private List<String> mStringList;
    private LayoutInflater mLayoutInflater;

    public MyRecyclerViewAdapter(Context context, List<String> list) {
        mContext = context;
        mStringList = list;
        mLayoutInflater = LayoutInflater.from(context);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.i("yxh", "onCreateViewHolder: ");
        View view = mLayoutInflater.inflate(R.layout.item_recycler_view, parent, false);
        MyViewHolder viewHolder = new MyViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.tv_recycler_view.setText(mStringList.get(position));
    }


    @Override
    public int getItemCount() {
        Log.i("yxh", "getItemCount: " + mStringList.size());
        return mStringList.size();
    }

    public  void add(int position){
        mStringList.add(position, "Add One");
        notifyItemInserted(position);           // notifyDateChanged()
    }

    public  void deleted(int position){
        mStringList.remove(position);
        notifyItemRemoved(position);
    }
}


class  MyViewHolder extends RecyclerView.ViewHolder {
    TextView tv_recycler_view;

    public MyViewHolder(View itemView) {
        super(itemView);
        tv_recycler_view = (TextView) itemView.findViewById(R.id.tv_item_recycler_view);
    }
}

  3、Item的分割线需要自定义,所以,这是在网上找到的。

DividerItemDecoration.java

     

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};             // 通过获取theme,而获取lineDivider

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;


    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);          // 通过获取theme,而获取lineDivider
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent) {
//		Log.v("recyclerview - itemdecoration", "onDraw()");
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();

        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView v = new RecyclerView(parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition,
                               RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }
}
     

     然后在RecyclerViewActivity中使用

   // 设置RecyclerView的分割线
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, LinearLayout.VERTICAL);
        mRecyclerView.addItemDecoration(dividerItemDecoration);
      

     4、Item的增加与删除的东西效果可以使用默认的,也可以使用自定义,github上就用已经有开源的可用https://github.com/wasabeef/recyclerview-animators

      所以,我们就直接拿来用就好了

  // 设置RecyclerView添加或删除的动画
        ScaleInAnimator animator = new ScaleInAnimator();
        mRecyclerView.setItemAnimator(animator);
    

     5、RecyclerView没有提供Item的方法,所以,需要我们自己去实现。 不过,也可以在网上找例子,我自己整理了一下。

       通过继承RecyclerView.onItemTouchListener 我们可以自定义item的点击以及长按效果

      RecyclerItemClickListener.java

**
 * Created by Administrator on 2015/9/17.
 *  创建RecyclerView的Item点击类
 *  网址:http://sapandiwakar.in/recycler-view-item-click-handler/
 *             http://stackoverflow.com/questions/24471109/recyclerview-onclick/26826692#26826692
 *             http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/
 */
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

    public interface  OnItemClickListener{
         void onItemClick(View view, int position);
         void onItemLongClick(View view, int position);
    }

    GestureDetector mGestureDetector;
    private OnItemClickListener mItemClickListener;

    public RecyclerItemClickListener(Context context, final RecyclerView view, OnItemClickListener listener){
        mItemClickListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View childView = view.findChildViewUnder(e.getX(), e.getY());
                if (childView != null && mItemClickListener != null){
                    mItemClickListener.onItemLongClick(view, view.getChildAdapterPosition(childView));
                }
            }
        });

    }
    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mItemClickListener != null && mGestureDetector.onTouchEvent(e)) {
            mItemClickListener.onItemClick(view, view.getChildAdapterPosition(childView));
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView rv, MotionEvent e) {

    }
}

   在RecyclerViewActivity中使用

    

 // 设置RecyclerView 的点击事件
        mRecyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(RecyclerViewActivity.this, mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Toast.makeText(RecyclerViewActivity.this, "item click position: " + position , Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {
                        Toast.makeText(RecyclerViewActivity.this, "item long click position: " + position , Toast.LENGTH_SHORT).show();
                    }
                })
        );

   

 

      











你可能感兴趣的:(RecyclerView 以及 ItemClickListener的实现)