Skip to content

Instantly share code, notes, and snippets.

@daichan4649
Last active August 26, 2016 08:50
Show Gist options
  • Save daichan4649/7924152 to your computer and use it in GitHub Desktop.
Save daichan4649/7924152 to your computer and use it in GitHub Desktop.
プログレス表示(IllegalStateException: Can not perform this action after onSaveInstanceState 対策済)
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.execute).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startProgressTask();
}
});
}
private void startProgressTask() {
new ProgressTask().execute();
}
class ProgressTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
showProgress();
}
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
hideProgress();
}
}
private static final String TAG_PROGRESS = "progress";
private void showProgress() {
DialogFragment dialog = new ProgressDialogFragment();
// 例外対策
// IllegalStateException: Can not perform this action after onSaveInstanceState
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(dialog, TAG_PROGRESS);
ft.commitAllowingStateLoss();
}
private void hideProgress() {
Fragment fragment = getFragmentManager().findFragmentByTag(TAG_PROGRESS);
if (fragment == null || !(fragment instanceof DialogFragment)) {
return;
}
((DialogFragment) fragment).dismissAllowingStateLoss();
}
}
public class ProgressDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
setCancelable(false);
ProgressDialog dialog = new ProgressDialog(getActivity());
dialog.setMessage("処理中..");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
return dialog;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment