I have a problem when I change from portrait to landscape orientation when programing a gallery. The page position in the method PageAdapter.instantiateItem(View container, int position) turns 0 when change the screen orientation. I want to store the current page position to keep in this page when the orientation changes.
You will need to store the currently displayed page in your saved instance state. For how to save state, please read the documentation.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the current item
savedInstanceState.putInt("current_item", pager.getCurrentItem());
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
After an orientation change, that state can be restored and used to set your pagers position.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentItem = savedInstanceState.getInt("current_item");
}
}
Call pager.setCurrentItem(mCurrentItem); e.g. in your onStart() or onResume() method.
For how to get and set the currently selected item read the ViewPager documentation:
getCurrentItem()
setCurrentItem()
Related
I have some data loaded from API call in AsyncTaskLoader. Everything is good but when screen rotates the scroll position goes to first as the adapter is set again on config changes( But the API call is not made as it's a Loader). I tried saving scroll position as suggested in the following links
link 1
I saved the the scroll state in onSavedInstanceState() and restored it on onRestoreInstanceState() also tried in onPause() and onResume() but the recyclerview always shows items from first position when rotating the screen.
Here is code to save and restore the scroll state in my app
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(LIST_STATE, mMoviesListRecycler.getLayoutManager().onSaveInstanceState());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
listScroll=savedInstanceState.getParcelable(LIST_STATE);
mMoviesListRecycler.getLayoutManager().onRestoreInstanceState(listScroll);
}
I have read a lot of things about the data save instance and restore but Unable to implement in my case. What is my case in application .
I am using the Activity (MainActivity) and calling the fragment in it let say ParentFragment
ParentFragment Calls the ChildFragment in it though ParentFragment has its own views such as TextViews which takes First name, Last name and age and below this part I am programatically calling the ChildFragment
So in this way I have 2 fragments in the MainActivity, which is being shown to the user at a time on the screen
**What I want **
I want when User has change the orientation the layout should also change but I also want that the text fields should maintain there data in them .
I want to save some more fragment variables and their data also on configuration changes and retrieve them after the new layout is set after screen orientation changed.
**Problems and Confusions **
I have no idea If i set the Fragment.setRetainInstance(true) then would my fragment still be able to receive the onConfiguration Change call back?
When I rotate my device, the fragment gets re-initialize and also my activity has the Asynctask and that runs again , i want my activity to hold the same data . How can I achieve that?
Please help me and give me some hint.
If you want to change layout on orientation change then,you should not handle configuration change by retaining the activity(by setting android:configChanges="orientation" value for corresponding activity defined in manifest) or by using setRetainInstance() in fragment.
For saving the fragment state on configuration change use
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(FIRST_NAME_VALUE_KEY, firstNameTextView.getText());
outState.putInt(LAST_NAME_VALUE_KEY, lastNameTextView.getText());
super.onSaveInstanceState(outState);
}
and for writing back state to the views in fragment use
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.my_fragment, container, false);
if (savedInstanceState != null) {
String firstName = savedInstanceState.getInt(FIRST_NAME_VALUE_KEY);
String lastName = savedInstanceState.getInt(LAST_NAME_VALUE_KEY);
firstNameTextView.setText(firstName);
lastNameTextView.setText(lastName);
}
return view;
}
You will receive onConfigurationChanged() callback by retaining activity.it is not related to Fragment.setRetainInstance(true).
To avoid running asynctask again,We can store data and retain it using following callbacks inside the activity.
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
// Save custom values into the bundle
savedInstanceState.putInt(SOME_VALUE, someIntValue);
savedInstanceState.putString(SOME_OTHER_VALUE, someStringValue);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
in onCreate(Bundle savedInstanceState) call back you can check for savedInstanceSate , based on that you can call u asynctask or retain values as below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
asyncTask.execute();
} else {
someIntValue = savedInstanceState.getInt(SOME_VALUE);
someStringValue = savedInstanceState.getString(SOME_OTHER_VALUE);
}
}
Hi iam trying to save the state of the fragment when one fragment is replaced with other fragment.
Consider in my Activity i have a fragmentA with textview-1 and textview-2. when i click on the textview-1 i am replacing fragmentA with fragmentB which has a list view.
Now when i click on the fragmentB list item iam getting the list value and updating the textview-1. same thing iam doing for textview-2 but when i return back, the textview-1 value is gone. How to save the state of the fragment A and its textview-1 value.
Tried as below
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
outState.putString("curChoice", strtext);
}
and in OnActivityCreated()
if (savedInstanceState != null) {
// Restore last state for checked position.
strtext = savedInstanceState.getString("curChoice", "");
//incrementdata(strtext);
}
But always the savedInstanceState is giving null.
When any Fragment is destroyed by the system, everything will just happen exactly the same as in an Activity. It means that every single member variables are also destroyed with the fragment. You will have to manually save and restore those variables through the onSaveInstanceState and onActivityCreated methods respectively.
There is no onRestoreInstanceState method inside a Fragment.
So you need to do something like as below code.
// These variable are destroyed along with Activity
private String var1,var2;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("VAR1", var1);
outState.putString("VAR2", var2);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
var1 = savedInstanceState.getInt("VAR1");
var2 = savedInstanceState.getString("VAR2");
}
Basically every single standard widget such as EditText, TextView, Checkbox and etc. are all already internally implemented those things. You may need to enable it for some View for example you have to set android:freezeText to true for TextView to use the feature.
I create an activity contain tabhost with 3 tabs, also define
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize">
in the manifest for changed orientation, it helps me to remain on the same tab on landscape mode. But when I create a new xml file for the landscape mode and I put it into res/layout-land.My problem is when I entered into 2nd or 3rd tab and changed to landscape mode it calls the xml in layout- land but tab host switches to 1st tab.Kindly help me on this.
thank you.
It's better to override #onSaveInstance to save the position of the current tab.
And in onCreate method you can check for the position and set the tab according to the position
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the current position of the tab
savedInstanceState.putInt(CURRENT_TAB, getTabHost().getCurrentTab());
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Check for the tabPosition Value
if (savedInstanceState != null) {
// Restore tab position from saved state and set to TaBHost
mCurrentTab= savedInstanceState.getInt(CURRENT_TAB);
}
//initialize the tabHost and tab
tabHost.setCurrentTab(mCurrentTab);
I have a fragment with one main fragment displayed on it. When I rotate the screen, the activity is beeing recreated. What would be the best way to store the info about currently displayed fragment for screen state restore purposes?
You can use the method onSaveInstanceState to store values in a bundle:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(MY_FIRST_KEY,valueToSave);
}
then you can restore the values in the method onRestoreInstanceState
#Override
protected void onRestoreInstanceState(Bundle inState) {
super.onRestoreInstanceState(inState);
valueToSave = inState.getString(MY_FIRST_KEY);
}
You can also set an xml attribute on TextViews and EditText called "freezeText" which saves any text that was set.