Is there an addHeaderView equivalent for RecyclerView?

后端 未结 19 1652
独厮守ぢ
独厮守ぢ 2020-11-21 23:35

I\'m looking for an equivalent to addHeaderView for a recycler view. Basically I want to have an image with 2 buttons be added as a header to the listview. Is there a differ

19条回答
  •  梦谈多话
    2020-11-22 00:30

    You can achieve it using the library SectionedRecyclerViewAdapter, it has the concept of "Sections", where which Section has a Header, Footer and Content (list of items). In your case you might only need one Section but you can have many:

    1) Create a custom Section class:

    class MySection extends StatelessSection {
    
        List myList = Arrays.asList(new String[] {"Item1", "Item2", "Item3" });
    
        public MySection() {
            // call constructor with layout resources for this Section header, footer and items 
            super(R.layout.section_header, R.layout.section_footer,  R.layout.section_item);
        }
    
        @Override
        public int getContentItemsTotal() {
            return myList.size(); // number of items of this section
        }
    
        @Override
        public RecyclerView.ViewHolder getItemViewHolder(View view) {
            // return a custom instance of ViewHolder for the items of this section
            return new MyItemViewHolder(view);
        }
    
        @Override
        public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
            MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
    
            // bind your view here
            itemHolder.tvItem.setText(myList.get(position));
        }
    }
    

    2) Create a custom ViewHolder for the items:

    class MyItemViewHolder extends RecyclerView.ViewHolder {
    
        private final TextView tvItem;
    
        public MyItemViewHolder(View itemView) {
            super(itemView);
    
            tvItem = (TextView) itemView.findViewById(R.id.tvItem);
        }
    }
    

    3) Set up your ReclyclerView with the SectionedRecyclerViewAdapter

    // Create an instance of SectionedRecyclerViewAdapter 
    SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
    
    MySection mySection = new MySection();
    
    // Add your Sections
    sectionAdapter.addSection(mySection);
    
    // Set up your RecyclerView with the SectionedRecyclerViewAdapter
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setAdapter(sectionAdapter);
    

提交回复
热议问题