Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 安卓開發 第六篇 我的安卓應用架構設計-----BaseActivity類

安卓開發 第六篇 我的安卓應用架構設計-----BaseActivity類

編輯:關於Android編程

BaseActivity是項目中所有activity的基類,含有一些公共的屬性和方法,同時控制toolbar的顯示,以及其他一些功能。。。

來看源碼:

/**
 * BaseActivity 是所有activity的基類,把一些公共的方法放到裡面
 * 

* Created by tianlai on 16-3-3. */ public abstract class BaseActivity extends AppCompatActivity implements BaseUiView { private ActivityComponent activityComponent; @Inject protected LayoutInflater inflater; @Inject protected Context context; @Inject protected AppPageManager appPageManager; protected Toolbar toolbar; protected LinearLayout rootView; protected BasePresenter presenter; protected LoadingDialog loadingDialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 使用依賴注入 initInjector(); injectActivity(activityComponent); //設置根布局 rootView = (LinearLayout) inflateView(R.layout.activity_base); setContentView(rootView); // 將當前activity加入ActivityManager中 appPageManager.addActivity(this); // 設置導航欄 toolbar = (Toolbar) find(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); initToolbar(toolbar); //初始化加載數據對話框 loadingDialog=new LoadingDialog(this); loadingDialog.setCanceledOnTouchOutside(false); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface loadingDialog) { presenter.cancleLoading(); } }); //初始化Presenter presenter = getPresenter(); if (presenter == null) { throw new NullPointerException("presenter 不能為 Null"); } else { presenter.oncreate(savedInstanceState, context); } } /** * 初始化Toolbar * * @param toolbar */ protected void initToolbar(Toolbar toolbar) { toolbar.setNavigationIcon(R.mipmap.ic_toolbar_navigation); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } /** * 設置頁面的標題 * * @param title */ protected void setPageTitle(String title) { setPageTitle(FontUtil.addColor("#F04877", title)); } /** * @param title */ protected void setPageTitle(CharSequence title) { toolbar.setTitle(title); } /** * @param resId */ protected void setNavigationIcon(int resId) { toolbar.setNavigationIcon(resId); } /** * // 加載ContentView的內容 * * @param view */ protected void setContentViewToRoot(View view) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout .LayoutParams.MATCH_PARENT); rootView.addView(view, params); } protected void setContentViewToRoot(int layoutId) { setContentViewToRoot(inflateView(layoutId)); } /** * 進行注入 * * @param activityComponent */ protected abstract void injectActivity(ActivityComponent activityComponent); /** * 獲取 ActivityModule * * @return */ protected ActivityModule getActivityModule() { return new ActivityModule(this); } /** * 獲取注入Activity的Presenter對象 * * @return */ protected abstract BasePresenter getPresenter(); /** * 隱藏Toolbar */ protected void hideToolbar() { toolbar.setVisibility(View.GONE); } /** * 把布局變成View * * @param layoutId * @return */ protected View inflateView(int layoutId) { return inflater.inflate(layoutId, null); } /** * 設置注入器 */ private void initInjector() { ApplicationComponent appComponent = getAppComponent(); appComponent.inject(this); activityComponent = DaggerActivityComponent.builder() .applicationComponent(appComponent) .activityModule(new ActivityModule(this)) .build(); } /** * 獲取 ApplicationComponent * * @return */ public ApplicationComponent getAppComponent() { return ((AppApplication) getApplication()).getAppComponent(); } /** * activityComponent的getter方法 * * @return */ public ActivityComponent getActivityComponent() { return activityComponent; } /** * 顯示頁面加載狀態 */ @Override public void showLoading() { if (loadingDialog != null && !loadingDialog.isShowing()) { loadingDialog.show(); } } /** * 加載完成,隱藏加載狀態 */ @Override public void loadingComplete() { if (loadingDialog != null && loadingDialog.isShowing()) { loadingDialog.dismiss(); } } @Override protected void onResume() { super.onResume(); presenter.onResume(this); Bugtags.onResume(this); } @Override protected void onPause() { super.onPause(); presenter.onPause(); Bugtags.onPause(this); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); presenter.onSave(outState); } @Override protected void onDestroy() { super.onDestroy(); appPageManager.removeActivity(this); presenter.onDestroy(); presenter = null; ToastUtil.cancleToast(); } /** * 生成Toolbar右邊Action按鈕 * * @param name * @param viewId * @return */ @SuppressLint("NewApi") public TextView addRightActionView(CharSequence name, int viewId) { TextView tv_right = new TextView(context); if (viewId == 0) { tv_right.setId(R.id.tv_right_action); } else { tv_right.setId(viewId); } tv_right.setTextColor(getResources().getColor(R.color.font_red)); tv_right.setText(name); tv_right.setCompoundDrawablePadding(DpUtil.dp2px(context, 3)); tv_right.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); tv_right.setGravity(Gravity.CENTER); Toolbar.LayoutParams layoutParams = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT); layoutParams.rightMargin = DpUtil.dp2px(context, 10); layoutParams.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT; tv_right.setLayoutParams(layoutParams); return tv_right; } /** * 生成Toolbar中心顯示titile的View * * @return */ @SuppressLint("NewApi") public TextView addCenterTitleView(String title, int viewId) { TextView tv_title = new TextView(context); if (viewId == 0) { tv_title.setId(R.id.tv_center_title); } else { tv_title.setId(viewId); } tv_title.setTextColor(getResources().getColor(R.color.font_red)); tv_title.setCompoundDrawablePadding(DpUtil.dp2px(context, 3)); tv_title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); tv_title.setGravity(Gravity.CENTER); Toolbar.LayoutParams layoutParams = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.CENTER; tv_title.setLayoutParams(layoutParams); if (title != null) { tv_title.setText(title); } return tv_title; } /** * 設置應用的字體不隨系統設置的更改而更改 */ @Override public Resources getResources() { Resources resources = super.getResources(); Configuration config = new Configuration(); config.setToDefaults(); resources.updateConfiguration(config, resources.getDisplayMetrics()); return resources; } public AppPageManager getAppPageManager() { return appPageManager; } public void setAppPageManager(AppPageManager appPageManager) { this.appPageManager = appPageManager; } /** * 獲取view * * @param viewId * @return */ public View find(int viewId) { return findViewById(viewId); } /** * 獲取view * * @param viewId * @return */ public View find(View parent, int viewId) { return parent.findViewById(viewId); } /** * 隱藏軟鍵盤 */ protected void hideIME() { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow( this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } }

BaseActivity中的有些方法是由於項目的需要而添加的,可能在其他項目中不需要,這點請大家自行忽略。

其中BaseUiView 是所有對view操作接口的基類:

/**
 * BaseUiView 是應用中所有UiView的頂級抽象類,適合抽取UiView的公共方法和屬性
 *
 * UiView:MVP架構中的V。
 *
 * Created by tianlai on 16-3-3.
 */
public interface BaseUiView {

    /**
     * showLoading 方法主要用於頁面請求數據時顯示加載狀態
     */
    public void showLoading();

    /**
     * showEmpty 方法用於請求的數據為空的狀態
     */
    public void showEmpty();

    /**
     * showError 方法用於請求數據出錯
     */
    public void showError();

    /**
     * showError 方法用於請求數據完成
     */
    public void loadingComplete();


}

下面來看一個具體的activity:

/**
 * LoginActivity app的登錄頁面
 * 

* Created by tianlai on 16-3-3. */ public class LoginActivity extends BaseActivity implements LoginView { @Inject LoginPresenter loginPresenter; @Bind(R.id.edt_account) EditText edtAccount; @Bind(R.id.edt_psw) EditText edtPsw; @Bind(R.id.tv_login) TextView tvLogin; @Bind(R.id.tv_register) TextView tvRegister; @Bind(R.id.tv_forgetpsw) TextView tvForgetpsw; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); View contentView = inflateView(R.layout.activity_login); setContentViewToRoot(contentView); ButterKnife.bind(this, contentView); hideToolbar(); } @OnClick({R.id.tv_login,R.id.tv_register,R.id.tv_forgetpsw}) public void OnClick(View v){ switch (v.getId()){ case R.id.tv_login: //進行登錄請求 loginPresenter.login(getPhoneNum(),getPasswd()); break; case R.id.tv_register: toRegisterPage(); break; case R.id.tv_forgetpsw: toResetPasswdPage(); break; } } @Override protected void injectActivity(ActivityComponent activityComponent) { activityComponent.inject(this); } @Override protected BasePresenter getPresenter() { return loginPresenter; } @Override public void showEmpty() { } @Override public void showError() { } @Override public void toRegisterPage() { startActivity(new Intent(this,RegisterActivity.class)); } @Override public String getPhoneNum() { return edtAccount.getText().toString().trim(); } @Override public String getPasswd() { return edtPsw.getText().toString().trim(); } @Override public void toMainPage() { startActivity(new Intent(this,MainActivity.class)); finish(); } @Override public void toResetPasswdPage() { startActivity(new Intent(this,ResetPswActivity.class)); } }

而LoginView :

/**
 *
 * Created by tianlai on 16-3-3.
 */
public interface LoginView extends BaseUiView {
    /**
     * 去到注冊頁面
     */
    public void toRegisterPage();

    /**
     * 獲取登錄手機號
     *
     * @return
     */
    public String getPhoneNum();

    /**
     * 獲取登錄密碼
     *
     * @return
     */
    public String getPasswd();

    /**
     * 去主頁面
     */
    public void toMainPage();

    /**
     * 去重置密碼頁面
     */
    public void toResetPasswdPage();
}

頁面布局(activity_login.xml):

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/bg_login" android:gravity="center" android:orientation="vertical">

    <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="用戶登錄" android:textcolor="@color/white" android:textsize="25sp" android:textstyle="bold">

    <edittext android:id="@+id/edt_account" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginleft="40dp" android:layout_marginright="40dp" android:paddingleft="8dp" android:paddingright="8dp" android:maxlength="20" android:singleline="true" android:textcolor="@color/font_black_light" android:textcolorhint="@color/hint_color" android:hint="@string/hint_account" android:layout_margintop="60dp" android:background="@color/white">

    <edittext android:id="@+id/edt_psw" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginleft="40dp" android:layout_marginright="40dp" android:paddingleft="8dp" android:singleline="true" android:paddingright="8dp" android:maxlength="16" android:textcolor="@color/font_black_light" android:textcolorhint="@color/hint_color" android:hint="@string/hint_psw" android:layout_margintop="20dp" android:background="@color/white">

    <textview android:id="@+id/tv_login" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginleft="40dp" android:layout_marginright="40dp" android:layout_margintop="40dp" android:background="@drawable/bg_btn_round_green_5" android:gravity="center" android:text="@string/login_now" android:textcolor="@color/whitesmoke" android:textsize="18sp">

    <textview android:id="@+id/tv_register" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginleft="40dp" android:layout_marginright="40dp" android:layout_margintop="20dp" android:background="@drawable/bg_btn_round_green_5" android:gravity="center" android:text="@string/register_now" android:textcolor="@color/whitesmoke" android:textsize="18sp">

    <textview android:id="@+id/tv_forgetpsw" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="15dp" android:gravity="center" android:text="@string/forget_psw" android:textcolor="@color/aqua" android:textsize="14sp">

</textview></textview></textview></edittext></edittext></textview></linearlayout></code>

最終效果:

這裡寫圖片描述

額,發現沒什麼可以說的了,就到這裡吧!<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwPrj8tuDXysHPo7o8L3A+DQo8cD7O0rXEZ2l0aHVitdjWt9LUvLDKudPDZGVtb6O6IDxhIGhyZWY9"https://github.com/naivor/naivorapp">https://github.com/naivor/naivorapp

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved