Minimal template code for Android development, RecyclerView implementation

I tried to summarize how to implement RecyclerView

I searched RecyclerView on the net and built the sample code that came out, but it didn't succeed at all. If there isn't much left, I decided to leave it, so I decided to summarize Recycer View. (And I have to use it at work)

What is RecyclerView?

In Android development, I used to implement up to ListView. However, it seems that ListView is not used much in recent Android, and RecyclerView is often used. The implementation in ListView wasn't that hard, but I couldn't find a decent RecyclerView sample code on the net, so I decided to make my own template. RecyclerView is like a higher version of ListView, and for me it's just an iOS UICollectionView-like image. It seems that it is suitable for displaying a large amount of list data, and it is made so that it can be scrolled efficiently by reusing screen parts.

About the source code for the template

RecyclerView.java


public class ScrollListActivity extends AppCompatActivity {

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

        android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setLogo(R.mipmap.ic_launcher);
        setSupportActionBar(toolbar);
        CollapsingToolbarLayout toolbarLayout = findViewById(R.id.toolbarLayout);
        toolbarLayout.setTitle(getString(R.string.toolbar_title));
        toolbarLayout.setExpandedTitleColor(Color.WHITE);
        toolbarLayout.setCollapsedTitleTextColor(Color.LTGRAY);

        RecyclerView lvMenu = findViewById(R.id.lvMenu);
        LinearLayoutManager layout = new LinearLayoutManager(ScrollListActivity.this);
        lvMenu.setLayoutManager(layout);
        List<Map<String,Object>> menuList = createTeishokuList();
        RecyclerListAdapter adapter = new RecyclerListAdapter(menuList);
        lvMenu.setAdapter(adapter);
    }

    private List<Map<String, Object>> createTeishokuList() {
        List<Map<String, Object>> menuList = new ArrayList<>();

        Map<String, Object> menu = new HashMap<>();
        menu.put("name", "Fried chicken set meal");
        menu.put("price", 800);
        menu.put("desc", "Fried young birds with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Hamburger set meal");
        menu.put("price", 850);
        menu.put("desc", "Hand-made hamburger steak with salad, rice and miso soup.");
        menuList.add(menu);

        //Repeat data registration below.
        menu = new HashMap<>();
        menu.put("name", "Ginger-grilled set meal");
        menu.put("price", 850);
        menu.put("desc", "Grilled ginger with grated ginger with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Steak set meal");
        menu.put("price", 1000);
        menu.put("desc", "Domestic beef steak with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Stir-fried vegetables set meal");
        menu.put("price", 750);
        menu.put("desc", "Seasonal stir-fried vegetables with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Tonkatsu set meal");
        menu.put("price", 900);
        menu.put("desc", "Loin pork cutlet with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Minced meat and set meal");
        menu.put("price", 850);
        menu.put("desc", "Hand-made minced meat cutlet with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Chicken cutlet set meal");
        menu.put("price", 900);
        menu.put("desc", "A hearty chicken cutlet with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Croquette set meal");
        menu.put("price", 850);
        menu.put("desc", "Hokkaido potato croquette with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Grilled fish set meal");
        menu.put("price", 850);
        menu.put("desc", "Grilled Spanish mackerel with salad, rice and miso soup.");
        menuList.add(menu);

        menu = new HashMap<>();
        menu.put("name", "Yakiniku set meal");
        menu.put("price", 950);
        menu.put("desc", "Salad, rice and miso soup are added to the special sauce.");
        menuList.add(menu);

        return menuList;
    }

    private class RecyclerListViewHolder extends RecyclerView.ViewHolder {
        public TextView _tvMenuName;
        public TextView _tvMenuPrice;
        public RecyclerListViewHolder(View itemView) {
            super(itemView);
            _tvMenuName = itemView.findViewById(R.id.tvMenuName);
            _tvMenuPrice = itemView.findViewById(R.id.tvMenuPrice);
        }
    }

    private class RecyclerListAdapter extends RecyclerView.Adapter<RecyclerListViewHolder> {
        private List<Map<String, Object>> _listData;
        public RecyclerListAdapter(List<Map<String, Object>> listData) {
            _listData = listData;
        }

        //Method to create viewholder object
        @Override
        public RecyclerListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(ScrollListActivity.this);
            View view = inflater.inflate(R.layout.row, parent, false);
            RecyclerListViewHolder holder = new RecyclerListViewHolder(view);
            return holder;
        }

        //Method to assign the data to be displayed to each screen part in the view holder
        @Override
        public void onBindViewHolder(RecyclerListViewHolder holder, int position) {
            Map<String, Object> item = _listData.get(position);
            String menuName = (String)item.get("name");
            int menuPrice = (Integer)item.get("price");
            String menuPriceStr = String.valueOf(menuPrice);
            holder._tvMenuName.setText(menuName);
            holder._tvMenuPrice.setText(menuPriceStr);
        }

        //Method that returns the number of data
        @Override
        public int getItemCount() {
            return _listData.size();
        }
    }
}

activity_scroll_list.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:elevation="10dp">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/toolbarLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                android:background="@color/colorPrimary"/>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

   <android.support.v7.widget.RecyclerView
       android:id="@+id/lvMenu"
       android:scrollbars="vertical"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        app:layout_anchor="@id/appbar"
        app:layout_anchorGravity="bottom|end"
        app:srcCompat="@android:drawable/ic_dialog_email"/>
</android.support.design.widget.CoordinatorLayout>

row.xml


<?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="wrap_content"
	android:orientation="vertical">

	<TextView
		android:id="@+id/tvMenuName"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_marginLeft="10dp"
		android:layout_marginTop="10dp"
		android:textSize="18sp"/>

	<LinearLayout
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:layout_marginBottom="10dp"
		android:layout_marginLeft="10dp"
		android:orientation="horizontal">

		<TextView
			android:id="@+id/tvMenuPrice"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:textSize="14sp"/>

		<TextView
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:text="@string/tv_menu_unit"
			android:textSize="14sp"/>

	</LinearLayout>

</LinearLayout>

About important class methods for using RecyclerView

RecyclerView.java


private class RecyclerListViewHolder extends RecyclerView.ViewHolder {}

You need to create a ViewHolder class that inherits from the RecyclerView.ViewHolder class. Is it the generation of View class like ʻUITableViewCell` in iOS image? It is said that the object that holds the screen parts of each item is called a view holder.

RecyclerView.java


private class RecyclerListAdapter extends RecyclerView.Adapter<RecyclerListViewHolder> {}

This is because RecyclerView does not have its own Adapter, so you need to customize and implement it yourself. Since recyclerView.Adapter is an abstract class, it seems that it is necessary to implement the following three methods.

onCreateViewHolder: Method to create viewholder object onBindViewHolder: Method to put display data in each screen part in view holder getItemCount: Method that returns the number of data

About screenshots

Screenshot_1530530217.png

Screenshot_1530530220.png

About implementing separators like UITableViewCell

Looking at the screenshot, it seems that the separator line like UITableViewCell is not implemented by default in the case of Recyclerview. A separate DividerItemDecoration class is required to insert the separator line.

To implement it, just add the following two lines at the bottom of the Activity's protected void onCreate (Bundle savedInstanceState) method.

RecyclerView.java


       //Create an object for the separator line
        DividerItemDecoration decoration = new DividerItemDecoration(ScrollListActivity.this, layout.getOrientation());
        lvMenu.addItemDecoration(decoration);

The separator line will now be displayed.

About click events

And if you actually tap RecyclerView to handle some action

RecyclerView.java


private class ItemClickListener implements View.OnClickListener

Just implement. Let's write the process in this private class method and set it in the following place.

RecyclerView.java


        //Method to create viewholder object
        @Override
        public RecyclerListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(ScrollListActivity.this);
            View view = inflater.inflate(R.layout.row, parent, false);
            view.setOnClickListener(new ItemClickListener()); // <-Add to here
            RecyclerListViewHolder holder = new RecyclerListViewHolder(view);
            return holder;
        }

The click event is now responsive.

Reference books

Develop basic and applied skills! Android application development textbook Practical hands-on to avoid becoming a developer

Recommended Posts

Minimal template code for Android development, RecyclerView implementation
First Android development for busy people
Library collection useful for Android development
Notes for Android application development beginners
Learning guidelines for Android development for iOS engineers
[Android] Implementation of side-scrolling ListView using RecyclerView
Sample code for Singleton implementation using enum
Preparation for Android development of POCOPHONE f1
A memorandum for android application development beginners
Sample code collection for Azure Java development
Android Studio development for the first time (for beginners)
Android Development App_Preparation