Reputation: 681
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
Reputation: 13143
"But when screen orientate, view is refreshing."
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
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.
Hope this helps!
Upvotes: 0
Reputation: 592
Create an interface:
public interface ClickCallback {
void onItemClicked(String id);
}
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)
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());
}
});
}
}
In OnCreate extract your color data:
public void onCreate(Bundle bundle) {
if (bundle != null) {
value = bundle.getInt("color");
}
}
Upvotes: 1