如何在适配器中扩展多个类?

时间:2016-04-28 10:00:28

标签: java android android-recyclerview multiple-inheritance sections

我想在列表中实现部分。我有一份任务清单。 List有一个自定义适配器,它扩展了recyclerview滑动适配器,因为我已经向recyclelerview实现了滑动手势。

现在,任务列表与已完成和待处理的任务一起显示。每个列表项都有一个复选框,显示任务已完成或待处理。

如果选中复选框,则任务完成,反之亦然。现在我想用标题创建两个部分。一个用于已完成的任务,另一个用于待处理的任务。

所以完成的任务应显示在已完成的部分内,反之亦然。此外,如果未检查任务,即挂起,如果用户选中复选框,则该项应从待处理部分中删除,并应添加到已完成的部分,反之亦然。

我在一个库中检查了部分。

https://github.com/afollestad/sectioned-recyclerview

但是当我尝试实现库时,我得到了错误,即适配器无法扩展两个类,因为我之前已经扩展了recyclelerview swipe库。

扩展sectionedRecyclerview适配器后的

onBindViewHolder方法我得到错误,因为IAdapter应该实现onBindViewHolder(VH,int)

如何解决这个问题?

适配器:

    public class IAdapter extends RecyclerSwipeAdapter<IAdapter.ItemViewHolder> , SectionedRecyclerViewAdapter<IAdapter.ItemViewHolder> {

    public ArrayList<Task> items;
    Context conext;
    public int _mId;

    List<Task> itemsPendingRemoval = new ArrayList<>();

    public IAdapter(Context context, ArrayList<Task> item) {
        this.conext=context;
       this.items=item;
    }

    @Override
    public int getSectionCount() {
        return 2;
    }

    @Override
    public int getItemCount(int section) {
        return items.size();

    }

    public static class ItemViewHolder extends RecyclerView.ViewHolder {
        Task task;
        CheckBox cb;
        SwipeLayout swipeLayout;
        TaskTableHelper taskTableHelper;
        ItemViewHolder(final View itemView) {
            super(itemView);

            taskTableHelper= new TaskTableHelper(itemView.getContext());
            swipeLayout = (SwipeLayout) itemView.findViewById(R.id.swipe);
            cb = (CheckBox) itemView.findViewById(R.id.checkbox);

        }
    }

    @Override
    public void onBindViewHolder(final ItemViewHolder itemViewHolder, int section,final int i, int absolutePosition) {

        itemViewHolder.cb.setText(items.get(i).getTitle());

        itemViewHolder.task = items.get(i);

        int taskId = itemViewHolder.task.getId();

        itemViewHolder.task = itemViewHolder.taskTableHelper.getTask(taskId);

        int status = itemViewHolder.task.getStatus();

        if(status == 0)
        {
            itemViewHolder.cb.setTextColor(Color.WHITE);
        }

        else {

            itemViewHolder.cb.setChecked(true);

            itemViewHolder.cb.setTextColor(Color.parseColor("#B0BEC5"));

        }


       itemViewHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {

                    itemViewHolder.cb.setTextColor(Color.parseColor("#B0BEC5"));

                    itemViewHolder.task.setStatus(1);

                    itemViewHolder.taskTableHelper.updateStatus(itemViewHolder.task);

                }
                else

                {

                    itemViewHolder.cb.setTextColor(Color.WHITE);

                    itemViewHolder.task.setStatus(0);

                    itemViewHolder.taskTableHelper.updateStatus(itemViewHolder.task);

                }

            }

        });



        final Task item = items.get(i);
        itemViewHolder.swipeLayout.addDrag(SwipeLayout.DragEdge.Right,itemViewHolder.swipeLayout.findViewById(R.id.bottom_wrapper_2));
        itemViewHolder.swipeLayout.setShowMode(SwipeLayout.ShowMode.LayDown);

        itemViewHolder.swipeLayout.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
            @Override
            public void onDoubleClick(SwipeLayout layout, boolean surface) {
                Toast.makeText(conext, "DoubleClick", Toast.LENGTH_SHORT).show();
            }
        });
        itemViewHolder.swipeLayout.findViewById(R.id.trash2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mItemManger.removeShownLayouts(itemViewHolder.swipeLayout);
                items.remove(i);
                notifyItemRemoved(i);
                notifyItemRangeChanged(i, items.size());
                mItemManger.closeAllItems();

                itemViewHolder.taskTableHelper.deleteTask(item);

                _mId = item.getAlertId();

                cancelNotification();

                Toast.makeText(view.getContext(), "Deleted " + itemViewHolder.cb.getText().toString() + "!", Toast.LENGTH_SHORT).show();
            }
        });

        itemViewHolder.swipeLayout.findViewById(R.id.done).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                itemViewHolder.task.setStatus(1);
                itemViewHolder.taskTableHelper.updateStatus(itemViewHolder.task);
                itemViewHolder.cb.setChecked(true);
                Toast.makeText(conext, "Task Completed.", Toast.LENGTH_SHORT).show();
            }
        });

        itemViewHolder.swipeLayout.getSurfaceView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                boolean mEditMode;

                int id = item.getId();
                int priority = item.getTaskPriority();
                String title = item.getTitle();
                String alertDate = item.getAlertDate();
                String alertTime = item.getAlertTime();
                String dueDate = item.getDueDate();
                String dueTime = item.getDueTime();
                _mId = item.getAlertId();

                int listId = item.getList();

                mEditMode = true;

                Intent i = new Intent(conext, AddTaskActivity.class);

                i.putExtra("taskId", id);
                i.putExtra("taskTitle", title);
                i.putExtra("taskPriority", priority);
                i.putExtra("taskAlertTime", alertTime);
                i.putExtra("taskAlertDate", alertDate);
                i.putExtra("taskDueDate", dueDate);
                i.putExtra("taskDueTime", dueTime);
                i.putExtra("taskListId", listId);
                i.putExtra("EditMode", mEditMode);
                i.putExtra("AlertId",_mId);

                conext.startActivity(i);

            }
        });


        mItemManger.bindView(itemViewHolder.itemView, i);

    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup viewGroup,int position) {

            View itemView = LayoutInflater.
                    from(viewGroup.getContext()).
                    inflate(R.layout.card_layout, viewGroup, false);
            return new ItemViewHolder(itemView);

    }



        @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }


    public void remove(int position) {
       Task item = items.get(position);
        if (itemsPendingRemoval.contains(item)) {
            itemsPendingRemoval.remove(item);
        }
        if (items.contains(item)) {
            items.remove(position);
            notifyItemRemoved(position);
        }
    }

    public void cancelNotification()
    {
        AlarmManager alarmManager = (AlarmManager)conext.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(conext, NotificationReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(conext,_mId, intent, 0);
        alarmManager.cancel(pendingIntent);
    }
    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swipe;
    }
}

请帮忙......谢谢..

3 个答案:

答案 0 :(得分:2)

您可以使用库SectionedRecyclerViewAdapter轻松实现此目的。

首先创建一个Section类来分组任务:

class TaskSection extends StatelessSection {

    String title;
    List<Task> list;

    public TaskSection(String title, List<Task> 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
    }

    public int addTask(Task task) {
        return list.add(task;
    }

    public int removeTask(Task task) {
        return list.remove(task;
    }

    @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).getTitle());
    }

    @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);
    }
}

然后使用您的章节设置RecyclerView:

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

// Create your sections with the list of data
TaskSection compSection = new TaskSection("Completed", compList);
TaskSection pendSection = new TaskSection("Pending", pendList);

// Add your Sections to the adapter
sectionAdapter.addSection(compSection);
sectionAdapter.addSection(pendSection);

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

现在,如果您要将任务从“待处理”部分发送到“已完成”:

pendSection.removeTask(task);
compSection.addTask(task);
sectionAdapter.notifyDataSetChanged();

答案 1 :(得分:1)

此示例还发布了您发布的链接。你可以像这样实现。

public class MainAdapter extends SectionedRecyclerViewAdapter<MainAdapter.MainVH> {

        @Override
        public int getSectionCount() {
            return 20; // number of sections.
        }

        @Override
        public int getItemCount(int section) {
            return 8; // number of items in section (section index is parameter).
        }

        @Override
        public void onBindHeaderViewHolder(MainVH holder, int section) {
            // Setup header view.
        }

        @Override
        public void onBindViewHolder(MainVH holder, int section, int relativePosition, int absolutePosition) {
            // Setup non-header view.
            // 'section' is section index.
            // 'relativePosition' is index in this section.
            // 'absolutePosition' is index out of all non-header items.
            // See sample project for a visual of how these indices work.
        }

        @Override
        public MainVH onCreateViewHolder(ViewGroup parent, int viewType) {
            // Change inflated layout based on 'header'. 
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(viewType == VIEW_TYPE_HEADER ? R.layout.header : R.layout.normal, parent, false);
            return new MainVH(v);
        }

        public static class MainVH extends RecyclerView.ViewHolder {

            public MainVH(View itemView) {
                super(itemView);
                // Setup view holder.
                // You'd want some views to be optional, e.g. for header vs. normal.
            }
        }
    }

答案 2 :(得分:0)

将回收站视图拆分为多个部分的最简单方法是使用包含标题和项目的布局,然后在标题相同时更改可见性。

布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tvHeader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:padding="16dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="@color/primary"
        android:textStyle="bold"
        tools:text="A" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvHeader"
        android:background="?android:attr/selectableItemBackground"
        android:padding="16dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        tools:text="Adam" />

</RelativeLayout>

适配器(2018年Kotlin版):

class ContactAdapter @Inject constructor() : RecyclerView.Adapter<ContactAdapter.ViewHolder>() {

    var onItemClick: ((Contact) -> Unit)? = null
    var contacts = emptyList<Contact>()

    override fun getItemCount(): Int {
        return contacts.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_contact, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val name = contacts[position].name
        holder.header.text = name.substring(0, 1)
        holder.name.text = name

        // if not first item, check if item above has the same header
        if (position > 0 && contacts[position - 1].name.substring(0, 1) == name.substring(0, 1)) {
            holder.headerTextView.visibility = View.GONE
        } else {
            holder.headerTextView.visibility = View.VISIBLE
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val headerTextView: TextView = itemView.tvHeader
        val nameTextView: TextView = itemView.tvName

        init {
            itemView.setOnClickListener {
                onItemClick?.invoke(contacts[adapterPosition])
            }
        }
    }
}

也可以提供帮助:RecyclerView itemClickListener in Kotlin

旧Java适配器版本:

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.DataViewHolder> {

    private List<Contact> mData;

    @Inject
    public RecyclerAdapter() {
        mData = new ArrayList<>();
    }

    public void setData(List<Contact> data) {
        mData = data;
    }

    public Contact getItem(int position){
        return mData.get(position);
    }

    @Override
    public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_contact, parent, false);
        return new DataViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final DataViewHolder holder, int position) {
        Contact contact = mData.get(position);
        holder.headerTextView.setText(contact.getName().substring(0, 1));
        holder.nameTextView.setText(contact.getName());

        // if not first item check if item above has the same header
        if (position > 0 && mData.get(position - 1).getName().substring(0, 1).equals(contact.getName().substring(0, 1))) {
            holder.headerTextView.setVisibility(View.GONE);
        } else {
            holder.headerTextView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public class DataViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.text_header)
        TextView headerTextView;
        @BindView(R.id.text_name)
        TextView nameTextView;

        public DataViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}