一個稍具規模的 App 裡,往往有十幾個 Activity 共用同一套 titlebar 或 footerbar。如果每個 Activity 都各自寫一遍,後續改動簡直是噩夢。合理的做法是在架構層抽出一個 BaseActivity,讓公共部分只存在一份。
實現思路是:BaseActivity 繼承 Activity,先加載一個「骨架」布局,其中為具體頁面預留一個空的容器;子類只需調用 baseSetContentView() 把自己的布局塞進這個容器,公共的頭尾自然就位。
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // 去掉系統標題,改用自定義 titlebar
setContentView(R.layout.base);
}
public void baseSetContentView(int layoutResId) {
LinearLayout llContent = (LinearLayout) findViewById(R.id.content);
LayoutInflater inflater =
(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(layoutResId, null);
llContent.addView(v);
}
}
外層是 RelativeLayout:頂部一個 50dip 高的 LinearLayout 作為標題欄,裡面依次是返回按鈕、標題文本、確認與取消按鈕;下方那個 id 為 content 的 LinearLayout 就是留給子頁面的空位。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="50dip"
android:background="@drawable/titlebar"
android:layout_alignParentTop="true"
android:orientation="horizontal">
<Button
android:id="@+id/titlbarback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/back"
android:textSize="14dip" />
<TextView
android:id="@+id/title"
style="@style/titlebarstyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
<Button
android:id="@+id/confirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/confirm"
android:textSize="14dip" />
<Button
android:id="@+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/cancel"
android:textSize="14dip" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="@+id/content">
</LinearLayout>
</RelativeLayout>
這樣一來,BaseActivity 的子類只要在 onCreate 中調用 baseSetContentView(R.layout.xxx),就自動獲得了統一的標題欄與頁腳。
這個骨架可以再往前推進幾步。其一,把標題文字、返回鍵與確認鍵的點擊事件封裝成 protected 方法(如 setTitle()、setOnBackClickListener()),子類按需覆蓋,比直接 findViewById 更內聚。其二,示例中 inflate(layoutResId, null) 傳 null 會丟失子布局根節點的 LayoutParams,實戰中應傳 llContent 並掛 attachToRoot = false,讓 margin 與匹配規則生效。其三,若頁面需要過渡動畫、埋點、統一的 Loading 與錯誤態,都可以放在 BaseActivity 的 onResume 或封裝方法中統一處理。最後,項目若已引入 Fragment 或 Jetpack 組件,也可考慮把公共部分下沉到 BaseFragment 或自定義容器 View,與 BaseActivity 形成一致的複用層。
更多 Android 相關內容可見 Android 專題頁面。