優雅なAndroidコードを書く方法について------BaseActivity

1780 ワード

名前から、BaseActivityはActivityのベースクラスであることがわかります.このベースクラスは、ActivityをsActivity Stackに追加/削除すること、Activity間のジャンプ、プロンプトボックスの表示など、Activityのほとんどの実装が必要な方法を実現しています.コードを見て
public class BaseActivity extends FragmentActivity {

	ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		ActivityManager.getInstance().push(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ActivityManager.getInstance().pop(this);
	}

	public void openActivity(Class> clazz) {
		openActivity(clazz, null);
	}

	public void openActivity(Class> clazz, Bundle bundle) {
		Intent intent = new Intent();
		intent.setClass(this, clazz);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		startActivity(intent);

	}

	protected void cancleProgressDialog() {
		if (mProgressDialog != null && !mProgressDialog.isShowing()) {
			mProgressDialog.cancel();
		}
	}

	protected void showLoadingDialog() {
		if (mProgressDialog != null) {
			mProgressDialog.show();
		} else {
			mProgressDialog = createProgressDialog();
			mProgressDialog.show();
		}

	}

	protected ProgressDialog createProgressDialog() {
		return null;
	}

	protected void showToast(int resId, boolean length) {
		Toast.makeText(this, resId,
				length ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
	}

	/**
	 * 
	 * @param msg
	 *             
	 * @param length
	 *            true ,false 
	 * @return: void
	 */
	protected void showToast(String msg, boolean length) {
		Toast.makeText(this, msg,
				length ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
	}
}
はいずれもActivityのベースクラスであり、継承すると必ずコードが優雅になります.