Подтвердить что ты не робот

Добавьте два раздела в андроид recyclerview

В моем приложении я использую recyclerview для отображения всего списка контактов. Я хочу два раздела в recyclerview.

Как и в одном разделе, мой список контактов для контактов и второй раздел - это список контактов телефона.

Как этот

enter image description here

Есть ли способ сделать это?

Кто-нибудь знает, как это сделать?

4b9b3361

Ответ 1

Если у вас уже есть RecyclerView, простой способ реализовать разделы - использовать Gabriele Mariotti SimpleSectionedRecyclerViewAdapter.

Я вставляю вам свой пример:

//Your RecyclerView
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,LinearLayoutManager.VERTICAL));

//Your RecyclerView.Adapter
mAdapter = new SimpleAdapter(this,sCheeseStrings);


//This is the code to provide a sectioned list
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
        new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();

//Sections
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0,"Section 1"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(5,"Section 2"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(12,"Section 3"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(14,"Section 4"));
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(20,"Section 5"));

//Add your adapter to the sectionAdapter
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
          SimpleSectionedRecyclerViewAdapter(this,R.layout.section,R.id.section_text,mAdapter);
mSectionedAdapter.setSections(sections.toArray(dummy));

//Apply this adapter to the RecyclerView
mRecyclerView.setAdapter(mSectionedAdapter);

Ответ 2

Если вы ищете решение, которое не нужно использовать жестко закодированные индексы заголовка/строки, вы можете использовать библиотеку SectionedRecyclerViewAdapter.

Сначала создайте класс раздела для группировки ваших элементов:

class MySection extends StatelessSection {

    String title;
    List<String> list;

    public MySection(String title, List<String> list) {
        // call constructor with layout resources for this Section header, footer and items 
        super(R.layout.section_header, R.layout.section_item);

        this.title = title;
        this.list = list;
    }

    @Override
    public int getContentItemsTotal() {
        return list.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(list.get(position));
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new SimpleHeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;

        // bind your header view here
        headerHolder.tvItem.setText(title);
    }

    public void addRow(String item) {
        this.list.add(item);
    }

}

Затем вы настраиваете RecyclerView с помощью разделов:

// Create an instance of SectionedRecyclerViewAdapter 
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

// Create your sections with the list of data
MySection favoritesSection = new MySection("Favorites", favoritesList);
MySection contactsSection = new MySection("Add Favorites", contactsList);

// Add your Sections to the adapter
sectionAdapter.addSection(favoritesSection);
sectionAdapter.addSection(contactsSection);

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);

Вы также можете добавлять новые строки в свои разделы без необходимости пересчитывать индексы:

favoritesSection.addRow("new item");
sectionAdapter.notifyDataSetChanged();

Ответ 3

Позвольте мне попытаться предложить собственное решение.

У вас должен быть список контактов с флагом isFavourite, например

private class Contacts{
  private String name;
  private String phoneNumber;
  private boolean isFavourite;
}

сортировать этот массив на основе isFavourite и contactName как это

передать этот список в ваш ContactRecyclerAdapter. и используйте два разных макета для заголовка и элементов , как это

Ответ 4

В вашем адаптере getItemViewType Layout как это....

@Override
    public int getItemViewType(int position) {
        if (mCountriesModelList.get(position).isSection) {
            return SECTION_VIEW;
        } else {
            return CONTENT_VIEW;
        }
    }

https://github.com/sayanmanna/LetterSectionedRecyclerView

Ответ 5

Взгляните на мою библиотеку на Github, можно легко создавать разделы: RecyclerAdapter и Easy Section

mRecylerView.setLayoutManager(...);
/*create Adapter*/
RecyclerAdapter<Customer> baseAdapter = new RecyclerAdapter<>(...);
/*create sectioned adapter. the Adapter type can be RecyclerView.Adapter*/
SectionedAdapter<String, RecyclerAdapter> adapter = new SectionedAdapter<>(SectionViewHolder.class, baseAdapter);
/*add your sections*/
sectionAdapter.addSection(0/*position*/, "Title Section 1");
/*attach Adapter to RecyclerView*/
mRecylerView.setAdapter(sectionAdapter);

Надеюсь, что это поможет.