我有一个将recyclerView呈现为列表的类(由数组中的元素数量定义),但是在合并数据类时遇到了麻烦。

public class Tab3 extends Fragment {
RecyclerView recyclerView;
String[] Items={"Item 0", "Item 1", "Item 2",};

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab3, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
    recyclerView.setAdapter(new Adapter(this.getActivity(), Items));

    return rootView;
    }
}


下面是应包含数据/适配器的类:

public class Adapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
String[] items ={"Item 0", "Item 1", "Item 2",};

public Adapter(Context context, String[] items) {
    this.context = context;
    this.items = this.items;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View row = inflater.inflate(R.layout.custom_row, parent, false);
    Item item = new Item(row);
    return item;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
    ((Item) holder).textView.setText(items[position]);
    ((Item) holder).toggleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context, "Clicked at position " + position, Toast.LENGTH_SHORT).show();
        }
    });
}

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

public class Item extends RecyclerView.ViewHolder {
    TextView textView;
    ToggleButton toggleButton;

    public Item(View itemView) {
        super(itemView);
        textView = (TextView) itemView.findViewById(R.id.item);
        toggleButton = (ToggleButton) itemView.findViewById(R.id.toggleButton);
    }
}
}


如果我删除线

String[] items ={"Item 0", "Item 1", "Item 2",};


从后一个类中,getItemCount()返回一个null(items.length)-但是,我无法弄清楚如何将其传递给另一段代码。

最佳答案

而不是在您的适配器中

String[] items ={"Item 0", "Item 1", "Item 2",};




String[] items;


和这个

this.items = this.items;




public Adapter(Context context, String[] items) {
        this.context = context;
        this.items = items;
}


您可以在getItemCount上进行检查,但我不认为有必要进行此检查。

@Override
public int getItemCount() {
 if (items != null) {
    return items.length;
    }
  return 0;
}

10-08 12:30
查看更多