How to use the same RecyclerView Adapter for different layouts

后端 未结 4 2164
逝去的感伤
逝去的感伤 2021-02-09 06:48

I am developing an application which heavily relies on the usage of RecyclerView.

I really need to know how to use the same RecyclerView for different item layouts. An e

4条回答
  •  不要未来只要你来
    2021-02-09 07:05

    I came across similar situation and here is the model i followed.

    First of all, Fragment layout file.

    fragment layout file is not going to change for all 3 fragments(basically it is similar to list fragment), so I created a template file for list fragment.

    list_fragment_template.xml
    
    
    
        
    
    
    

    Now fragment code :

    In my case all the 3 fragments do almost same stuff (get recycler view, get adapter, recycler view decoration and some more operations etc).

    Created an AbstrctFragment which extends fragment and overrided onCreate onAttach onDestroy etc. Since only type of data recyclerview consumes and adapters to push data to recycelrview would change for each of the fragment, create an abstract function to getAdapter and templatize data. Each of the three fragments will be derived from this AbstractFragment.

        public abstract class AbstractFragment extends Fragment {
    
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            // Inflate the layout for this fragment
            View view = inflater.inflate(R.layout.template_list_fragment, container, false);
    
    
                mRecyclerView = (RecyclerView) view.findViewById(R.id.list);
    
                // get adapter to show item list
                // and fetch data.
                mRecyclerAdapter = getAdapter();
                mRecyclerView.setAdapter(mRecyclerAdapter);
    
                // show it as vertical list
                mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                // add seperator between list items.
                mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
    
    return view;
        }
    

    ... onAttach onDetach and whatever common memberfunctions and member variables that comes for each fragment.

    Now RecyclerView layout files. Since all of them are different in layout, obviously they must be different.

    RecyclerViewAdapters : Again here common code would be to member declarations, CreateViewHolder (here only layout name changes rest all code is same) and any other function which all of these adapters would share. (something like filtering list items).

    similar to how we did for fragments, you can keep this in AbstractRecyclerViewAdapter and make bindViewholder etc as abstract functions and have 3 different recyclerAdapters which would derive from this AbstractRecyclerViewAdapter..

提交回复
热议问题