bateler8
bateler8

Reputation: 105

Changing ArrayList shown in RecyclerView Android Java

I have multiple array lists inside an arraylist :

[[Object1, Object2],[Object3, Object4],[Object5, Object6]]

I display the first array list in a recyclerview that displays one arraylist at a time:

myViewHolder.bindTo(cities.get(0).get(i));

I want to click a button in another class that would show change the array list shown. How would I achieve this?

Recycler View Adapter Class:

    private List<List<Country>> cities;

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        PlannerItemBinding plannerItemBinding =
                DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.planner_item, viewGroup, false);

        return new MyViewHolder(plannerItemBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        myViewHolder.bindTo(cities.get(0).get(i));

    }

    @Override
    public int getItemCount() {
        if (cities != null) {
            return cities.size();
        } else {
            return 0;
        }
    }

    public void setCityList(List<List<Country>> cities) {
        this.cities = cities;
        notifyDataSetChanged();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private PlannerItemBinding plannerItemBinding;

        public MyViewHolder(@NonNull PlannerItemBinding plannerItemBinding) {
            super(plannerItemBinding.getRoot());

            this.plannerItemBinding = plannerItemBinding;
        }

        void bindTo(Country country) {
            plannerItemBinding.setVariable(com.example.planner.BR.city, country);
            plannerItemBinding.setVariable(com.example.planner.BR.adapterPosition, getLayoutPosition());
            plannerItemBinding.setVariable(com.example.planner.BR.countryImageMedium, country.getImages().get(0).getSizes().getMedium());
            plannerItemBinding.executePendingBindings();

        }
    }

}

Upvotes: 0

Views: 766

Answers (2)

jeprubio
jeprubio

Reputation: 18002

Set a setter in your RecyclerView.Adapter:

public updateCities(List<List<Coutry>> cities) {
    this.cities = cities;
    notifydatasetchanged();
}

so that you can call it in onClick() of that button with the new data.

This will update the model of your adapter with the passed data and notify the recyclerview that its data has changed.

Upvotes: 2

Biscuit
Biscuit

Reputation: 5247

You create an onClickListener on the object of your choice, and then when it is clicked you just setCityList to the new data and use notifydatasetchanged on your adapter

Upvotes: 1

Related Questions