Simple use of RecyclerView

Posted by Alkimuz on Tue, 18 Jun 2019 22:13:42 +0200

Use of RecyclerView

1 Introducing recyclerView

In the build.gradle file in moudle, find dependencies and add a reference to recyclerView:

compile 'com.android.support:recyclerview-v7:24.2.0'

In fact, the design package contains many controls related to Material Design, including recyclerView code, so you can also use recyclerView by referring to the design package:

compile 'com.android.support:design:23.2.0'

Note: The referenced version of the dependency package needs to be consistent with its own build tools version before it can be used

2 Write a recyclerView in xml

Add a Recycler View to MainActivity for display. The code is as follows:

<!--Omitted...-->
        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/recyclerView"/>
<!--Omitted...-->

3 Setting data for recyclerView in java

The code in MainActivity is as follows:

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

    private void initData() {
        ArrayList<String> datas = new ArrayList<>();
        for(char i ='A';i<='Z';i++){
            datas.add(i+"");
        }
        mAdapter = new MyAdapter(datas);
        rv.setAdapter(mAdapter);
    }

    private void initView() {
        rv = (RecyclerView) findViewById(R.id.recyclerView);
        //You have to specify the effect of the display and set up a LayoutManager, otherwise there will still be a blank space.
        LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
        rv.setLayoutManager(llm);
    }

The code in MyAdapter is as follows:

public class MyAdapter extends RecyclerView.Adapter {

    private ArrayList<String> datas;
    private Context mContext;

    public MyAdapter(Context applicationContext, ArrayList<String> datas) {
        this.datas = datas;
        this.mContext = applicationContext;
    }

    //Adadapter of RecyclerView has integrated ViewHolder
    //Two sections of logic 1 in getView create view object (converting xml to view) 2 find some controls in view object and set up some display.

    //Execute the first logic in onCreateViewHolder, create a view, set it to a ViewHolder, and return the holder
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //The third parameter is false, and if true, the view generated is actually the parent to which the second parameter points, causing an error.
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_recyclerview, parent,false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    //Setting data for controls in holder
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ((MyViewHolder)holder) .mTextView.setText(datas.get(position));
    }

    //How many item s do Count control controls have?
    @Override
    public int getItemCount() {
        return datas.size();
    }
}

class MyViewHolder extends RecyclerView.ViewHolder{

    public TextView mTextView;

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

4. Set up different display effects for recyclerView

Setting up multiple buttons to modify the different display modes of recyclerView

<LinearLayout  android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/action_listview"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="listView"
        app:showAsAction="never"/>
    <Button
        android:id="@+id/action_gridview"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="gridView"/>
    <Button
        android:id="@+id/action_hor_gridview"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="Horizontal gridView"/>
    <Button
        android:id="@+id/action_stagger"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="Staggered waterfall flow"/>
</LinearLayout>

Then in MainActivity, modify the menu code:

   @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_listview:
                LinearLayoutManager llm = new LinearLayoutManager(this);
                rv.setLayoutManager(llm);
                break;
            case R.id.action_gridview:
                GridLayoutManager rlm = new GridLayoutManager(this, 3);
                rv.setLayoutManager(rlm);
                break;
            case R.id.action_hor_gridview:
                GridLayoutManager hrlm = new GridLayoutManager(this, 3,
                        GridLayoutManager.HORIZONTAL, false);
                rv.setLayoutManager(hrlm);
                break;
            case R.id.action_stagger:
                StaggeredGridLayoutManager sglm = new StaggeredGridLayoutManager(3,
                        StaggeredGridLayoutManager.VERTICAL);
                rv.setLayoutManager(sglm);
                break;
        }
    }

It's just that different Layout Managers are set up for RecyclerView.

5. Setting up methods to add and delete item s to RecyclerView

Set up two methods for Adapter first

/**
 * Method of Adding Item
 * @param position Location added
 * @param item  What's added (take String for example)
 */
public void addItem(int position, String item){

}

/**
 * Method of deleting Item
 * @param position Deleted location
 */
public void deleteItem(int position){

}

Then it gives the corresponding method to implement the function, which can directly modify the contents of the collection.

/**
 * Method of Adding Item
 * @param position Location added
 * @param item  What's added (take String for example)
 */
public void addItem(int position, String item){
    mDatas.add(position,item);
    //notifyDataSetChanged(); 
    notifyItemInserted(position);
}

/**
 * Method of deleting Item
 * @param position Deleted location
 */
public void deleteItem(int position){
    mDatas.remove(position);
  //notifyDataSetChanged();
    notifyItemRemoved(position);
}

Normally ListView uses notify DataSetChanged (); this method is refreshed and recyclerView uses its corresponding

(Add notify Item Inserted (position); (Delete notify Item Removed (position);) Method, animation effect will be generated when modifying the corresponding item

Add two more buttons to insert and delete data when clicked. Modify the xml code as follows:

<LinearLayout  android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
    ...
    <Button
        android:id="@+id/action_add"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="Add to"/>
    <Button
        android:id="@+id/action_delete"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:text="delete"/>
</LinearLayout>

The method code for calling in MainActivity is as follows:

   @Override
    public void onClick(View v) {
        switch (v.getId()) {
            ...
            case R.id.action_add:
                mAdapter.addItem(2,"Added");
                break;
            case R.id.action_delete:
                mAdapter.deleteItem(2);
                break;
        }
    }

6. Set animation effects for RecyclerView

Through rv.setItemAnimator(); set animation, which can be a new related class, and achieve the corresponding method to write their own needs to achieve the animation effect.

rv.setItemAnimator(new DefaultItemAnimator());
rv.setItemAnimator(new RecyclerView.ItemAnimator() {});
rv.setItemAnimator(new SimpleItemAnimator() {});

By searching, we found an animation effect set of recyclerView on GitHub, which can basically satisfy the needs of animation effect: [recyclerView animators][ https://github.com/wasabeef/recyclerview-animators]

By putting the corresponding animation objects below into the method, the corresponding animation effect can be achieved.

Cool

LandingAnimator

Scale

ScaleInAnimator, ScaleInTopAnimator, ScaleInBottomAnimator

ScaleInLeftAnimator, ScaleInRightAnimator

Fade

FadeInAnimator, FadeInDownAnimator, FadeInUpAnimator

FadeInLeftAnimator, FadeInRightAnimator

Flip

FlipInTopXAnimator, FlipInBottomXAnimator

FlipInLeftYAnimator, FlipInRightYAnimator

Slide

SlideInLeftAnimator, SlideInRightAnimator, OvershootInLeftAnimator, OvershootInRightAnimator

SlideInUpAnimator, SlideInDownAnimator

The code is as follows:

LandingAnimator scaleInAnimator = new LandingAnimator();
rv.setItemAnimator(scaleInAnimator);

ScaleInAnimator animator = new ScaleInAnimator();
rv.setItemAnimator(animator);
...

7 Add click effects to ReyclerView

RecyclerView does not provide an OnItemClick-related item click method, which needs to be implemented by itself. This is achieved through the Adapter. In the Adapter, we first customize an OnItemClickListener, then in the onBindViewHolder method of the Adapter, we set OnClickListener for holder.itemView, and call the customized OnItemClickListener in the click method of the OnClickListener. The code is as follows:

    //Setting data for controls in holder
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        ((MyViewHolder)holder) .mTextView.setText(datas.get(position));
        //Add a click to item
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Toast.makeText(mContext, click item + position, Toast. LENGTH_SHORT). show ();
                mOnItemClickListener.onItemClick(position,holder.itemView);
            }
        });
    }

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

    private OnItemClickListener mOnItemClickListener = null;

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

Then you can set up a custom OnItemClickListener in MainActivity. The code is as follows:

    private void initData() {
        ....
        mAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View itemView) {
                Toast.makeText(MainActivity.this, "position: "+position, Toast.LENGTH_SHORT).show();
            }
        });
    }

8 Set partition lines for RecyclerView

Unlike ListView, RecyclerView does not have a set partition line and needs to be handled by itself. Setting a partition line for RecyclerView requires the following code to be executed:

rv.addItemDecoration(new RecyclerView.ItemDecoration() {

            String str = "I am the dividing line.";
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
               ....
                    c.drawText(str,left,top,paint);
                }
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                //Setting the displacement spacing between item s by outRect
                outRect.set(0,0,0,getStringHeight(paint));
            }
        });

You need to set up an ItemDecoration for RecyclerView. If you don't want to implement the method, you can refer to some tripartite libraries, such as: [recyclerview-flexible edivider][ https://github.com/yqritc/RecyclerView-FlexibleDivider]

Topics: Android xml github Gradle