Last active
August 26, 2016 08:50
-
-
Save daichan4649/7924152 to your computer and use it in GitHub Desktop.
プログレス表示(IllegalStateException: Can not perform this action after onSaveInstanceState 対策済)
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 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(); | |
} | |
} |
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 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