什么是RecyclerView.Adapter等效于ArrayAdapter的getView方法

时间:2017-11-06 02:11:13

标签: android android-recyclerview android-arrayadapter

我正在将ScrollView转换为RecyclerView。在我的一种方法中,我最初声明了这一点:

View item = listAdapter.getView(i, null, (ViewGroup) template);

listAdapter最初是ArrayAdapter,但是我写了一个新的RecyclerView.Adapter,现在它已经被声明了。我想知道如何重写上面的陈述,因为RecyclerView.Adapter没有getView方法。

1 个答案:

答案 0 :(得分:0)

使用 RecyclerView ,不同的是,您管理 RecyclerView.Adapter 类中的所有数据:

如果您使用 ViewHolder 编写 RecyclerView.Adapter ,则可以将 getView 纳入 RecyclerView.Adapter 你写的课。 它位于 onBindViewHolder 方法

你只需要这样称呼它:

holder.itemView

这是我作为示例编写的 RecyclerViewAdapter 类,展示了如何在 onBindViewHolder 中调用 itemView 我为 itemView 分配了一个 onItemClickListener ,我还有2个 TextViews (在底部的 ViewHolder 中声明) )

        public class SampleRecyclerAdapter extends RecyclerView.Adapter<SampleRecyclerAdapter.ViewHolder> {
            private ArrayList<Order> orderList;
            private LayoutInflater mLayoutInflater;
            private Context context;

        public SampleRecyclerAdapter(Context context, ArrayList<Order> orderList) {
            this.orderList = orderList;
            this.mLayoutInflater = LayoutInflater.from(context);
            this.context = context;
        }

        @Override
        public SampleRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = mLayoutInflater.inflate(R.layout.recycler_item_order, parent, false);
            return new SampleRecyclerAdapter.ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final SampleRecyclerAdapter.ViewHolder holder, int position) {
            final Order order = orderList.get(position);
            holder.date.setText(order.getFormattedDate()+", "+ order.getFormattedTime());
            holder.orderNumber.setText(order.getUid());

    //Here, calling itemView (equivalent of listAdapter.getView()) and setting a onClickListener as an example. You can do whatever you want.
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, OrderDetailActivity.class);
                    intent.putExtra("order", order);
                    context.startActivity(intent);
                }
            });
        }

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

  //In the ViewHolder you declare all the components of your xml layout for you recyclerView items ( and the data is assigned in the onBindViewHolder, above)  
        class ViewHolder extends RecyclerView.ViewHolder {

            private TextView date, orderNumber;

            private ViewHolder(View itemView) {
                super(itemView);
                date = (TextView) itemView.findViewById(R.id.textViewDate);
                orderNumber = (TextView) itemView.findViewById(R.id.textViewOrderNumber);
            }
        }
    }