Created
August 7, 2016 15:30
-
-
Save crazyhitty/bb2e0ba20bb818f53dd962a1a5f7e968 to your computer and use it in GitHub Desktop.
Maintaining savedInstanceState in a fragment. Source: http://stackoverflow.com/a/13306633
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
// Only set fragment when saved instance is null | |
if(savedInstanceState==null) { | |
FragmentManager fragmentManager = getSupportFragmentManager(); | |
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); | |
fragmentTransaction.replace(R.id.frame_layout_main, | |
MainActivityFragment.newInstance(), | |
MainActivityFragment.class.getSimpleName()); | |
fragmentTransaction.commit(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivityFragment extends Fragment { | |
private static final String ARG_TEXT="TEXT"; | |
private TextView mTxtView; | |
public static MainActivityFragment newInstance() { | |
MainActivityFragment fragment = new MainActivityFragment(); | |
return fragment; | |
} | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, | |
Bundle savedInstanceState) { | |
View view = inflater.inflate(inflater, R.layout.fragment_main, container, false); | |
bindViews(view); | |
return view; | |
} | |
private void bindViews(View view){ | |
mTxtView=(TextView)view.findViewById(R.id.text_view); | |
} | |
@Override | |
public void onActivityCreated(@Nullable Bundle savedInstanceState) { | |
super.onActivityCreated(savedInstanceState); | |
// Check if the text is already available in the savedInstanceState bundle, if available | |
// set it on the textView. | |
if(savedInstanceState!=null){ | |
String text=savedInstanceState.getString(ARG_TEXT); | |
mTxtView.setText(text); | |
}else { | |
mTxtView.setText("No data available"); | |
} | |
} | |
@Override | |
public void onSaveInstanceState(Bundle outState) { | |
super.onSaveInstanceState(outState); | |
outState.putString(ARG_TEXT, "hello fragment !"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment