Simple use of RecycleView

This control is used to display a large number of datasets in a limited window. In fact, we are not new to this kind of control, such as ListView and GridView.
With ListView and GridView, why do you need RecyclerView?
RecyclerView architecture provides a plug-in experience, high degree of decoupling and exceptional flexibility. It can achieve beautiful results by setting different LayoutManager, itemdecoration and itemanimator it provides.
*To control how it is displayed, use the layout manager LayoutManager
*Control the interval between items (paintable), please use ItemDecoration
*To control the animation of Item addition and deletion, please use ItemAnimator
*It is recommended to use interface callback to control click and long press events

Don't talk much
 Oh, by the way, forget to add dependency!
compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
A recycleview in the layout

<android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#ff0000"
        android:dividerHeight="5dp" />

Menu (this file needs to create a new menu file in res directory and save it)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/item1"
        android:title="ListView"
        app:showAsAction="never"></item>
    <item
        android:id="@+id/item2"
        android:title="GridView"
        app:showAsAction="never"></item>
    <item
        android:id="@+id/item3"
        android:title="WaterFall"
        app:showAsAction="never"></item>
</menu>
item layout of recycleview
 Hehe, there is only one TextView. It's a little simpler for the time being!
<?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="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/list_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40dp" />

</LinearLayout>

Because it is simple to use, the user-defined data is temporarily used

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerview;
    private ArrayList<String> list;
    private MyAdapter myAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();//Load recycleview control
        initData();//Initialization data
        myAdapter = new MyAdapter();
        //Set the layout manager < mainly to specify how to display data >
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        //Set adapter
        recyclerview.setAdapter(myAdapter);
        //Add a split line (this is the system default)
        recyclerview.addItemDecoration(new ItemDirection(this, ItemDirection.VERTICAL_LIST));
        //Add the change animation of the item (this animation is also the default of the system and can be customized)
        recyclerview.setItemAnimator(new DefaultItemAnimator());
        //Click event of item
        myAdapter.setItemClick(new OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                //See which Item you clicked on
                Toast.makeText(MainActivity.this, "" + list.get(position), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //Create menu options (click menu in the top right corner of the title bar)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    //Click event of menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item1:
                //LinearLayoutManager() displays data in listview
                recyclerview.setLayoutManager(new LinearLayoutManager(this));
                break;
            case R.id.item2:
                //GridLayoutManager() displays data in a GridView way
                recyclerview.setLayoutManager(new GridLayoutManager(this, 2));
                break;
            case R.id.item3:
                //StaggeredGridLayoutManager() is displaying data in waterfall flow, like Kwai Fu.
                recyclerview.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    //Initialize simulation data
    private void initData() {
        list = new ArrayList<String>();
        for (int i = 'A'; i <= 'Z'; i++) {
            list.add("" + (char) i);
        }
    }

    //Load control
    private void initView() {
        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);
    }
    /*
    *RecyclerView It focuses on the flexibility of layout. Although it can replace ListView, it doesn't even have basic click events
    *Define the interface and use it for the click event. The principle is like writing personal information for the teacher in the exam
    *The final purpose is to simulate the setOnItemClickListener() method of ListView. The caller only needs to call something similar to setOnItemClickListener to get the relevant data of the clicked item.
    principle
    Set setOnClickListener for each sub item of RecyclerView, and then call the external encapsulated interface in onClick again to pass the event to the external caller. "Set the setOnClickListener for each sub item of RecyclerView" is set in the Adapter. In fact, it can fully handle item click events directly in onClick, but this will destroy the logic of the code.
    */
    private interface OnItemClickListener {
        public void OnItemClick(View view, int position);
    }
    //Set the adapter < note that you must inherit the adapter from recycleview >
    public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
        private OnItemClickListener onItemClickListener;

        //Create a viewholder instance
        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //Load the layout of recycleview
            View view = View.inflate(MainActivity.this, R.layout.listview, null);
            //Call viewholder and pass the layout in
            MyViewHolder myViewHolder = new MyViewHolder(view);
            return myViewHolder;
        }

        //Bind data to item
        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            holder.item.setText(list.get(position));
            //Call interface, simulate Click
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //Call the click method in the interface, pass in the layout and index
                    onItemClickListener.OnItemClick(holder.itemView, position);
                }
            });
        }

        //Number of entries
        @Override
        public int getItemCount() {
            return list.size();
        }

        //Define a public method through which you can click item when an external class calls
        public void setItemClick(OnItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }
    }

    //Use viewholder to optimize layout
    private class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView item;
        //Note: itemview is the layout file passed in
        public MyViewHolder(View itemView) {
            super(itemView);
            item = itemView.findViewById(R.id.list_item);
        }
    }
}

Custom split line (it's for reference from friends. It seems that it's not very good. Of course, you can learn the principle of customization)

public class ItemDirection extends RecyclerView.ItemDecoration {
    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public ItemDirection(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        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) {

        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);
            android.support.v7.widget.RecyclerView v = new android.support.v7.widget.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);
        }
    }
}

Tags: Android xml encoding

Posted on Tue, 05 May 2020 01:15:12 -0700 by tempi