RecyclerView-:没有连接适配器;跳过布局

时间:2017-05-10 08:39:07

标签: android android-recyclerview android-adapter recycler-adapter

我一直在阅读stackoverflow帖子中的不同答案,并尝试实施他们的解决方案,但我仍然收到错误

public class Appetizer extends AppCompatActivity {

    private RecyclerView recyclerView;
        private AdapterFood mAdapter;


     recyclerView = (RecyclerView)findViewById(R.id.lvaptzr);
                   mAdapter = new AdapterFood(Appetizer.this,data);
                   recyclerView.setAdapter(mAdapter);
                   recyclerView.setLayoutManager(new LinearLayoutManager(Appetizer.this));

这是我的Adapter类:

public class AdapterFood extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context context;
    private LayoutInflater inflater;
    List<DataFood> data = Collections.emptyList();
    DataFood current;
    int currentPos=0;

    public AdapterFood(Context context, List<DataFood> data){
        this.context=context;
        inflater=LayoutInflater.from(context);
        this.data=data;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.list_item,parent,false);
        Myholder holder=new Myholder(view);
        return holder;

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Myholder myholder=(Myholder) holder;
        DataFood current=data.get(position);
        myholder.textFoodname.setText(current.foodName);
        myholder.textPrice.setText("Rp. " + current.price);
        myholder.textId.setText(current.foodId);
        Glide.with(context).load("http://kelompokdua.hol.es/pic/" + current.foodImage)
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .into(myholder.ivFood);
    }

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

    class Myholder extends RecyclerView.ViewHolder{
        TextView textFoodname,textPrice,textId;
        ImageView ivFood;

        public Myholder(View itemView) {
            super(itemView);
            textFoodname=(TextView) itemView.findViewById(R.id.textFoodname);
            ivFood=(ImageView)itemView.findViewById(R.id.ivFood);
            textId=(TextView)itemView.findViewById(R.id.textid);
            textPrice=(TextView) itemView.findViewById(R.id.textPrice);
        }
    }
}

我尝试任何方法,但我无法解决这些问题。我做错了什么?

1 个答案:

答案 0 :(得分:2)

您应该在 setLayoutManager 之前致电 setAdapter

    recyclerView = (RecyclerView)findViewById(R.id.lvaptzr);
    LinearLayoutManager mLayoutManager = new LinearLayoutManager(Appetizer.this);
    recyclerView.setLayoutManager(mLayoutManager); // 1st
    mAdapter= new AdapterFood(Appetizer.this,data);
    recyclerView.setAdapter(mAdapter);  // 2nd