Talisman
Talisman

Reputation: 388

Item Array in a RecyclerView

I have a class that renders the recyclerView as a list (which is defined by the number of elements in the array), but am having trouble merging the data class.

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

Below is the class that should contain the data/adapter:

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

If I remove the line

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

from the latter class, getItemCount() returns a null (items.length) - however, I cannot figure out how to pass that over to the other piece of code.

Upvotes: 0

Views: 84

Answers (1)

lakshay
lakshay

Reputation: 713

Instead of this in your adapter

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

to

String[] items;

and this

this.items = this.items;

to

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

you can make a check at your getItemCount but I don't think so there is any need to make this check.

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

Upvotes: 2

Related Questions