简体   繁体   中英

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

        }
    }

}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM