SoFunction
Updated on 2025-04-09

Android RecyclerView loads two layout methods

When the RecyclerView has a pull-down refresh, sometimes the list reflected in the design drawing has a header layout. This can be loaded through Adapter. Here we take loading two layouts as an example.

Let's take a look at Adapter's code:

import ;
import ;
import .;
import ;
import ;
import ;
import ;

import ;

import ;
import ;

public class MainListAdapter extends <>{
 private List<Data> list;
 private ArrayList<ItemEntity> jdList;
 private Context context;

 public MainListAdapter(List<Data> list,ArrayList<ItemEntity> jdList, Context context) {
   = list;
   = jdList;
   = context;
 }
 @Override
 public int getItemViewType(int position) {
  return (position).getShowType();
 }
 @Override
 public  onCreateViewHolder(ViewGroup parent, int viewType) {
  if(viewType==1){
   View view = (()).inflate(.layout_header_main_list,parent,false);
   return new HeaderHolder(view);
  }else{
   View view = (()).inflate(.item_list_main,parent,false);
   return new ViewHolderItem(view);
  }
 }

 @Override
 public void onBindViewHolder( holder, int position) {

  if(holder instanceof HeaderHolder){
   final HeaderHolder headerHolder = (HeaderHolder) holder;
   //TODO implements related logic  }else if(holder instanceof ViewHolderItem){

  }
 }

 @Override
 public int getItemCount() {
  return ();
 }

 private class HeaderHolder extends {

  HeaderHolder(View itemView) {
   super(itemView);
  }
 }

 private class ViewHolderItem extends {

  ViewHolderItem(View itemView) {
   super(itemView);
  }
 }


}

getItemViewType() returns the current layout type of the list. When Adapter loads the layout, the alignment is judged, that is, the corresponding judgment logic is implemented in the onBindViewHolder() method.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.