Last active
July 8, 2021 03:45
-
-
Save vamsitallapudi/26030c15829d7be8118e42b1fcd0fa42 to your computer and use it in GitHub Desktop.
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 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.getInstance(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"; | |
private RetainFragment() { | |
} | |
public static RetainFragment getInstance(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); | |
} | |
public 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