About
Key value pair structure
Articles Related
Snippet
Bundle args = new Bundle();
args.putInt("key",value);
Usage
Fragment Arguments
fragment.setArguments(Bundle bundle)
// Once the argument are set, you can only read from them
getArguments().getInt(key",0);
savedInstanceState Bundle
Thee savedInstanceState Bundle is restoring information once the fragment has been running. The bundle can save information:
- across orientation changes
- or if the application gets killed by the system (that's why you get it on the onCreateView methods)
- In the onSaveInstanceState method, you can save the values
@Override
public void onSaveInstanceState(Bundle outState) {
// When tablets rotate, the currently selected list item needs to be saved.
// When no item is selected, mPosition will be set to Listview.INVALID_POSITION,
// so check for that before storing.
if (mPosition != ListView.INVALID_POSITION) {
outState.putInt(SELECTED_KEY, mPosition);
}
super.onSaveInstanceState(outState);
}
- Retrieve it in the onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Code
// ...........
// If there's instance state, mine it for useful information.
// The end-goal here is that the user never knows that turning their device sideways
// does crazy lifecycle related things.
if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
// The listview probably hasn't even been populated yet. The poisition is then stored in a member variable
// Actually perform the swapout in onLoadFinished.
mPosition = savedInstanceState.getInt(SELECTED_KEY);
}
return myView;
}
- Use it
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
myAdapter.swapCursor(data);
if (mPosition != ListView.INVALID_POSITION) {
// If we don't need to restart the loader, and there's a desired position to restore,
mListView.smoothScrollToPosition(mPosition);
}
}