tsniso
tsniso

Reputation: 681

How to keep data in recycler view when screen orientation from portrait to landscape?

I have a custom object array to show in recycler view and I'm using GridLayout manager for my recylerview and showing (2x4),(3x3) etc. squares. When user click these squares it's color changed.

But when screen orientate, view is refreshing.

My question is how to keep this data (selected square's color ) when screen orientation ?

Upvotes: 1

Views: 822

Answers (3)

Vihaan Verma
Vihaan Verma

Reputation: 13143

"But when screen orientate, view is refreshing."

  • on screen rotation a new instance of the activity is created

You can have a ViewModel class which stores your arraylist of data including their current state. When activity is recreated via rotation this will be persisted and you will get the correct state.

Ref : https://medium.com/androiddevelopers/viewmodels-a-simple-example-ed5ac416317e

Upvotes: 0

Lakshan Dissanayake
Lakshan Dissanayake

Reputation: 561

You can store statuses of each square in a proper format and save them on onSaveInstanceState and retrieve them on onCreate method and manipulate the adapter as for your requirement.

Read more...

Hope this helps!

Upvotes: 0

Alexander Gapanowich
Alexander Gapanowich

Reputation: 592

  1. Create an interface:

    public interface ClickCallback {
    
    void onItemClicked(String id);
    }
    
  2. In your activity create a callback and pass it to your adapter like this:

    ClickCallback callback = new ClickCallback() {
            @Override
            public void onItemClicked(String id) {
                //your list item object must have a method to get color
                color = yourDataList.get(id).getColor();
    
            }
        };
    
        protected void onSaveInstanceState(Bundle bundle) {
       super.onSaveInstanceState(bundle);
       bundle.putInt("color", color);
       }
    
       YourAdapter adapter = new YourAdapter (yourDataList, callback) 
    
  3. In your adapter don't forget to set OnClickListener and call appropriate method, it could be like this:

           public ListItemViewHolder(View itemView) {
            super(itemView);
           //your code
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callback.onItemClicked(getAdapterPosition());
                }
            });
        }
    }
    
    1. In OnCreate extract your color data:

         public void onCreate(Bundle bundle) {
         if (bundle != null) {
         value = bundle.getInt("color");
         }
      }
      

Upvotes: 1

Related Questions