Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public class RetainFragEgActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button b = (Button) findViewById(R.id.aaa);
b.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
RetainFragment retainFragment =
RetainFragment.findOrCreateRetainFragment(getFragmentManager());
retainFragment.loadAsync();
}
});
}
private void handleResponse(String response) {
// do something with the response...
}
public static class RetainFragment extends Fragment {
private static final String TAG = "RetainFragment";
public RetainFragment() {
}
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
if (fragment == null) {
fragment = new RetainFragment();
fm.beginTransaction().add(fragment, TAG).commit();
}
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
private void loadAsync() {
new AsyncTask<Void, Void, String>() {
@Override protected String doInBackground(Void... params) {
// Do some work...
return null;
}
@Override protected void onPostExecute(String response) {
MyActivity myActivity = (MyActivity)getActivity();
if (myActivity != null) {
myActivity.handleResponse(response);
}
}
}.execute();
}
}
}
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.