編輯:關於 Android 程式設計
做專案的時候,對話框、載入進度、下拉重新整理、彈出式選單這幾樣東西幾乎每個 App 都躲不掉。麻煩的是每次都要重新翻開源專案找一次、改一次,時間就這樣被吃掉了。
這份 demo 就是把網路上常見的開源實作做過一次整理與抽取:只留下真正高頻使用的對話框、進度提示、下拉重新整理與 Popup 彈出層,再把它們收攏到一層簡潔的基礎類別裡。目錄結構刻意壓到最扁平,註解直接寫在程式碼上,方便整段複製到自己的專案,也方便往上繼續擴充。
完整專案可至下方連結下載。


從結構圖就能大致判斷每個檔案負責什麼。類別數量確實偏多,全部貼出來篇幅會失控,有興趣直接抓原始碼看。以下挑幾個最關鍵的基礎類別來拆。
螢幕尺寸、Toast、Loading 框、頁面跳轉、非同步任務管理——這些在每個 Activity 裡都會重複出現的東西,全部提到基礎類別裡,之後各頁只要繼承就能直接用。
public class BaseActivity extends Activity {
protected LoadingDialog mLoadingDialog;
/** 螢幕寬度、高度、密度 */
protected int mScreenWidth;
protected int mScreenHeight;
protected float mDensity;
/** 非同步任務清單,方便統一取消 */
protected List mAsyncTasks = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLoadingDialog = new LoadingDialog(this, "請求提交中");
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
mScreenWidth = metric.widthPixels;
mScreenHeight = metric.heightPixels;
mDensity = metric.density;
}
protected void putAsyncTask(AsyncTask asyncTask) {
mAsyncTasks.add(asyncTask.execute());
}
/** 頁面離開前把未完成的任務全部取消,避免記憶體洩漏 */
protected void clearAsyncTask() {
Iterator iterator = mAsyncTasks.iterator();
while (iterator.hasNext()) {
AsyncTask asyncTask = iterator.next();
if (asyncTask != null && !asyncTask.isCancelled()) {
asyncTask.cancel(true);
}
}
mAsyncTasks.clear();
}
protected void showLoadingDialog(String text) {
if (text != null) {
mLoadingDialog.setText(text);
}
mLoadingDialog.show();
}
protected void dismissLoadingDialog() {
if (mLoadingDialog.isShowing()) {
mLoadingDialog.dismiss();
}
}
/** 四組 Toast 快捷方法:長短顯示 × 字串資源/純字串 */
protected void showShortToast(int resId) { ... }
protected void showShortToast(String text) { ... }
protected void showLongToast(int resId) { ... }
protected void showLongToast(String text) { ... }
/** 自訂版面配置的 Toast */
protected void showCustomToast(String text) {
View toastRoot = LayoutInflater.from(this).inflate(R.layout.common_toast, null);
((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
Toast toast = new Toast(this);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastRoot);
toast.show();
}
/** 便於閱讀的 Log 包裝 */
protected void showLogDebug(String tag, String msg) { Log.d(tag, msg); }
protected void showLogError(String tag, String msg) { Log.e(tag, msg); }
/** 頁面跳轉,可選帶 Bundle */
protected void startActivity(Class cls) { startActivity(cls, null); }
protected void startActivity(Class cls, Bundle bundle) {
Intent intent = new Intent();
intent.setClass(this, cls);
if (bundle != null) {
intent.putExtras(bundle);
}
startActivity(intent);
}
}
PopupWindow 每寫一次就要重複設定背景、找 View、綁事件。這裡把它抽象成 abstract 類別,強制子類別實作 initViews()、initEvents()、init() 三段,順便提供「水平居中顯示於 parent 上方」與「顯示於 parent 正中央」兩個常用定位方法,以及一個單一的確認回呼介面。
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public abstract class BasePopupWindow extends PopupWindow {
protected View mContentView;
protected onSubmitClickListener mOnSubmitClickListener;
public BasePopupWindow(View contentView, int width, int height) {
super(contentView, width, height, true);
mContentView = contentView;
setBackgroundDrawable(new BitmapDrawable());
initViews();
initEvents();
init();
}
public abstract void initViews();
public abstract void initEvents();
public abstract void init();
/** 之後找子 View 不必再自己 mContentView.findViewById */
public View findViewById(int id) {
return mContentView.findViewById(id);
}
/** 顯示在 parent 上方並水平居中 */
public void showViewTopCenter(View parent) {
showAtLocation(parent, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
}
/** 顯示在 parent 正中央 */
public void showViewCenter(View parent) {
showAtLocation(parent, Gravity.CENTER, 0, 0);
}
public void setOnSubmitClickListener(onSubmitClickListener l) {
mOnSubmitClickListener = l;
}
public interface onSubmitClickListener {
void onClick();
}
}
這個基礎配接器只負責資料源管理與 position 換算,把 getView() 留給子類別實作。建構子同時支援可變參數與 List 兩種傳入方式,寫 demo 或簡單列表時特別省事。
public class BaseArrayListAdapter extends BaseAdapter {
protected Context mContext;
protected LayoutInflater mInflater;
protected List mDatas = new ArrayList();
/** 用字串陣列(可變參數)帶入資料 */
public BaseArrayListAdapter(Context context, String... datas) {
mContext = context;
mInflater = LayoutInflater.from(context);
if (datas != null && datas.length > 0) {
mDatas = Arrays.asList(datas);
}
}
/** 用 List 帶入資料 */
public BaseArrayListAdapter(Context context, List datas) {
mContext = context;
mInflater = LayoutInflater.from(context);
if (datas != null && datas.size() > 0) {
mDatas = datas;
}
}
@Override public int getCount() { return mDatas.size(); }
@Override public Object getItem(int position) { return mDatas.get(position); }
@Override public long getItemId(int position) { return position; }
/** 交給子類別決定每一列的樣子 */
@Override public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
}
主頁面用五顆按鈕分別觸發 Loading 框、單選列表對話框、輸入型對話框、Popup 彈出層,以及跳轉下拉重新整理頁面。
public class MainActivity extends BaseActivity
implements OnClickListener, ChatPopupWindow.onChatPopupItemClickListener {
protected SimpleListDialog mDialog;
private int mCheckId = 0;
private ChatPopupWindow mChatPopupWindow;
private int mWidth;
private int mHeaderHeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
initPopupWindow();
}
/** 單選列表對話框:用匿名內部類實作監聽 */
public void onSimpleListItem() {
String[] modes = new String[]{"測試一", "測試二", "測試三"};
mDialog = new SimpleListDialog(this);
mDialog.setTitle("單選框");
mDialog.setTitleLineVisibility(View.GONE);
mDialog.setAdapter(new CheckListDialogAdapter(mCheckId, this, modes));
mDialog.setOnSimpleListItemClickListener(new DialogItemClickListener());
mDialog.show();
}
protected class DialogItemClickListener implements onSimpleListItemClickListener {
@Override
public void onItemClick(int position) {
mCheckId = position;
}
}
/** 輸入型對話框:同時綁定取消與確認 */
private void onEditTextDialog() {
final EditTextDialog dialog = new EditTextDialog(this);
dialog.setTitle("填寫推薦人");
dialog.setButton("取消", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface d, int which) { dialog.cancel(); }
}, "確認", new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface d, int which) {
String text = dialog.getText();
if (text == null) {
dialog.requestFocus();
} else {
dialog.dismiss();
}
}
});
dialog.show();
}
/** 用 dp 換算好寬度與高度,避免不同螢幕密度跑版 */
protected void initPopupWindow() {
mWidth = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 130, getResources().getDisplayMetrics());
mHeaderHeight = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 48, getResources().getDisplayMetrics());
mChatPopupWindow = new ChatPopupWindow(this, mWidth, LayoutParams.WRAP_CONTENT);
mChatPopupWindow.setOnChatPopupItemClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
showLoadingDialog("正在加載。。。");
new Handler().postDelayed(new Runnable() {
@Override public void run() { dismissLoadingDialog(); }
}, 10000);
break;
case R.id.button2:
onSimpleListItem();
break;
case R.id.button3:
onEditTextDialog();
break;
case R.id.button4:
RelativeLayout layoutShow = (RelativeLayout) findViewById(R.id.layoutShow);
mChatPopupWindow.showAtLocation(
layoutShow, Gravity.RIGHT | Gravity.TOP, -10, mHeaderHeight + 10);
break;
case R.id.button5:
startActivity(PullRefreshListViewActivity.class);
break;
}
}
@Override public void onVoiceModeClick() { showCustomToast("pop監聽1"); }
@Override public void onCreateClick() { showCustomToast("pop監聽2"); }
@Override public void onSynchronousClick() { showCustomToast("pop監聽3"); }
}
刷新動作放在 AsyncTask 的 doInBackground 裡,做完才切回主執行緒更新配接器並呼叫 onRefreshComplete() 收起提示;使用者中途放手則走 onCancel()。這裡用 Thread.sleep 模擬網路延遲,實務上換成真正的請求即可。
public class PullRefreshListViewActivity extends BaseActivity
implements OnRefreshListener, OnCancelListener, OnItemClickListener {
private PullRefreshListView mRefreshListView;
String[] modes = new String[]{"測試一", "測試二", "測試三"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_refresh);
initViews();
}
protected void initViews() {
mRefreshListView = (PullRefreshListView) findViewById(R.id.otherfeedlist_mmrlv_list);
mRefreshListView.setAdapter(new CheckListDialogAdapter(1, this, modes));
mRefreshListView.setOnItemClickListener(this);
mRefreshListView.setOnRefreshListener(this);
mRefreshListView.setOnCancelListener(this);
}
@Override
public void onCancel() {
mRefreshListView.onRefreshComplete();
}
@Override
public void onRefresh() {
putAsyncTask(new AsyncTask() {
@Override
protected Boolean doInBackground(Void... params) {
try {
Thread.sleep(2000); // 這裡替換成真正的網路請求
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// 更新配接器資料後收合提示
mRefreshListView.onRefreshComplete();
}
});
}
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// 列表單擊事件依需求實作
}
}
這套結構的價值不在程式碼多漂亮,而在「改一次、到處可用」。基礎類別刻意保持單一職責,要換 Loading 動畫就只動 LoadingDialog,要換列表樣式就只動配接器,彼此不互相牽連。實際套用時,建議先把 com.org.base 整包搬過去,再按專案需要往下長出新的子類。
用 HttpURLConnection 在 Android 客戶端與伺服器之間傳遞物件
一般情況下,客戶端與伺服器的資料互動多使用 JSON 或 XML。相比 XML,JSON 更輕量、更省流量。但無論用哪一種,我們通常都得先把資料封裝成字串再傳輸。那麼,有
Android 高仿滑動驗證碼:自定義 Path、摳圖與動畫實現
效果目標滑動驗證碼常見於需要基本防機器人的情境。使用者需拖動滑塊,使驗證碼拼圖對齊指定位置。若在 Android 中自行實作,可以透過自定義 View 完成繪製、拖曳、驗
Material Design 新元件實戰:FloatingActionButton、TextInputLayout、Snackbar 與 TabLayout
在 2015 年的 Google I/O 大會上,Android 新版本 M 正式亮相——從這版開始,Android 不再以數字命名版本。這次更新幅度不算大,主要是把
Android 瀑布流借鏡 ListView 的回收與更新機制
在 Android 開發中,瀑布流常用於展示大量圖片內容。若只使用 ScrollView 堆疊子 View,雖然畫面效果容易完成,但當圖片數量增加時,記憶體使用量也會快速