Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Manage Fragment when rotating
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
......
if (getFragmentManager().findFragmentById(R.id.fragment) == null) {
getFragmentManager().beginTransaction().replace(R.id.fragment, new MainActivityFragment()).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
MainActivityFragment fragment = (MainActivityFragment) getFragmentManager().findFragmentById(R.id.fragment);
if (fragment.webView.canGoBack()) {
fragment.webView.goBack();
} else {
super.onBackPressed();
}
}
}
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
WebView webView;
public MainActivityFragment() {
}
@Override
public void onResume() {
super.onResume();
setRetainInstance(true);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
webView.saveState(outState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
webView.restoreState(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Log.i("fragment", "onCreateView");
webView = (WebView) view.findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
if (savedInstanceState == null) {
webView.loadUrl("http://www.google.com");
}
return view;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.