无法为RecyclerView.Adapter中的特定textView指定值

时间:2016-01-27 15:34:53

标签: android recycler-adapter

我是Android开发人员的新手,我想用片段创建app并在其中使用RecyclerView。我收到错误,说我正在尝试在null对象上使用setText。 我的代码看起来像这样:

public static class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {
        private static String[] newsTitle = new String[] {...};
        private static String[] newsDescs = new String[] {...};

        public ContentAdapter(ViewGroup parent) {}

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

        public static class ViewHolder extends RecyclerView.ViewHolder {
            TextView titles;
            TextView descs;
            public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
                super(inflater.inflate(R.layout.item_list, parent, false));
                titles = (TextView) parent.findViewById(R.id.list_title);
                descs = (TextView) parent.findViewById(R.id.list_desc);
            }
        }

         @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
             return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
         }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            holder.titles.setText(newsTitle[position]); //Here is error
            holder.descs.setText(newsDescs[position]); 
        }

        @Override
        public int getItemCount() { return newsTitle.length; }
    }

1 个答案:

答案 0 :(得分:1)

如果是视图持有者,这是一个正确的例子

public static class HeaderVH extends RecyclerView.ViewHolder {

    public TextView textView;

    public HeaderVH(View view){
        super(view);
        textView = (TextView)view;
    }

}

您需要将行的View对象传递给viewholder,而不是父View对象。这是onCreateViewHolder()

的一个例子
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_setting_header, parent, false);
      RecyclerView.ViewHolder  vh = new HeaderVH(v);
return vh;
}

https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html

https://www.bignerdranch.com/blog/recyclerview-part-1-fundamentals-for-listview-experts/