編輯:關於 Android 程式設計
本文基於 CSDN 上一位前輩的經典文章改進而來。原作者的面向對象設計思路非常清晰,值得細讀。以下是我在學習過程中整理出的幾個可借鑑之處。
把每個 Tab 的標識定義成 2 的幂,這樣就能用按位與一次判斷多個標誌位,效率比常規 switch 更高:
public class Constant {
public static final int SIGN_FRAGMENT_MESSAGE = 0x01 << 1;
public static final int SIGN_FRAGMENT_CONTACTS = 0x01 << 2;
public static final int SIGN_FRAGMENT_NEWS = 0x01 << 3;
public static final int SIGN_FRAGMENT_SETTENGS = 0x01 << 4;
}
使用時用 & 判斷:
@Override
public void onClickCallBack(int itemID) {
String tag = "";
if ((itemID & Constant.SIGN_FRAGMENT_MESSAGE) != 0) {
tag = Constant.STR_FRAGMENT_MESSAGE;
} else if ((itemID & Constant.SIGN_FRAGMENT_CONTACTS) != 0) {
tag = Constant.STR_FRAGMENT_CONTACTS;
} else if ((itemID & Constant.SIGN_FRAGMENT_NEWS) != 0) {
tag = Constant.STR_FRAGMENT_NEWS;
} else if ((itemID & Constant.SIGN_FRAGMENT_SETTENGS) != 0) {
tag = Constant.STR_FRAGMENT_SETTINGS;
}
mHeaderPanelLayout.setText(tag);
setTabSection(tag);
}
底部欄中間那兩個按鈕要和兩側均勻分佈,硬編碼 margin 在不同屏幕上一定會歪。正確做法是在 onLayout 裡實時計算剩餘空間:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
layoutItem(l, t, r, b);
}
private void layoutItem(int left, int top, int right, int bottom) {
int allChildWidth = 0;
int num = getChildCount();
for (int i = 0; i < num; i++) {
allChildWidth += getChildAt(i).getWidth();
}
int absoluteWidth = right - left - getPaddingLeft() - getPaddingRight();
// 可用空白均分到中間兩個按鈕的左間距上
int blankWidth = (absoluteWidth - allChildWidth) / (num - 1);
LayoutParams params1 = (LayoutParams) mContactsBtn.getLayoutParams();
params1.leftMargin = blankWidth;
mContactsBtn.setLayoutParams(params1);
LayoutParams params2 = (LayoutParams) mNewsBtn.getLayoutParams();
params2.leftMargin = blankWidth;
mNewsBtn.setLayoutParams(params2);
}
方式一:LayoutInflater,在自定義 View 構造函數中直接 inflate:
public ImageText(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.image_text_layout, this, true);
mImageView = (ImageView) findViewById(R.id.iv_imgae_text);
mTextiew = (TextView) findViewById(R.id.tv_imgae_text);
}
方式二:onFinishInflate(),適合在 XML 中直接寫出自定義控件的場景。此時解析完成後系統會回調該方法,正好用來批量查找子 View:
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mMessageBtn = (ImageText) findViewById(R.id.message_btn);
mContactsBtn = (ImageText) findViewById(R.id.contacts_btn);
mNewsBtn = (ImageText) findViewById(R.id.news_btn);
mSettingsBtn = (ImageText) findViewById(R.id.settings_btn);
initClickEvent();
}
這是 iOS 開發中最常用的設計模式,在 Android 裡同樣好用。底部欄只負責「改變自身樣式」和「對外拋出事件」,至於點擊後要做什麼,交給外部實現者決定:
public class BottomPanelLayout extends RelativeLayout implements OnClickListener {
private BottomPanelCallBackProtocal mCallBackProtocal;
public void setCallBackProtocal(BottomPanelCallBackProtocal callBackProtocal) {
this.mCallBackProtocal = callBackProtocal;
}
public interface BottomPanelCallBackProtocal {
void onClickCallBack(int itemID);
}
@Override
public void onClick(View v) {
initBottomPanel();
int index = -1;
switch (v.getId()) {
case R.id.message_btn:
index = Constant.SIGN_FRAGMENT_MESSAGE;
mMessageBtn.setChecked(index);
break;
case R.id.contacts_btn:
index = Constant.SIGN_FRAGMENT_CONTACTS;
mContactsBtn.setChecked(index);
break;
case R.id.news_btn:
index = Constant.SIGN_FRAGMENT_NEWS;
mNewsBtn.setChecked(index);
break;
case R.id.settings_btn:
index = Constant.SIGN_FRAGMENT_SETTENGS;
mSettingsBtn.setChecked(index);
break;
}
if (mCallBackProtocal != null) {
mCallBackProtocal.onClickCallBack(index);
}
}
}
Activity 實現該協議,響應就被解耦出去了:
public class MainActivity extends Activity
implements BottomPanelCallBackProtocal {
@Override
public void onClickCallBack(int itemID) {
// 同上一節的按位判斷,切換 Fragment
setTabSection(tag);
}
}
原來的 ensureTransaction() 在粘貼和消除時都要判斷一次,其實沒必要。事務只需要一個開始點,後續複用同一個對象即可:
private void setTabSection(String tag) {
if (TextUtils.equals(tag, currFagTag)) {
return;
}
ensureTransaction();
if (currFagTag != null && !currFagTag.equals("")) {
detachFragment(getFragment(currFagTag));
}
attachFragment(R.id.fragment_panel, getFragment(tag), tag);
commitTransaction();
}
private void ensureTransaction() {
if (mFragmentTransaction == null) {
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
}
}
場景:在 MessageFragment 裡點擊 TextView,跳到 ContactFragment 並把數據帶過去。
1)源頭 Fragment 觸發跳轉
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getActivity().findViewById(R.id.msg_tv).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity) getActivity()).setTabSection(Constant.STR_FRAGMENT_CONTACTS);
}
});
}
2)目標 Fragment 聲明數據代理
// 存儲本 Fragment 更新所需的參數
private ContactFragmentCallBack mContactFragmentCallBack;
public interface ContactFragmentCallBack {
// 更新時需要一個 String
String getContentStr();
}
3)源頭 Fragment 實現該代理
public class MessageFragment extends BaseFragment
implements ContactFragmentCallBack {
@Override
public String getContentStr() {
return "abc";
}
}
4)目標 Fragment 在 onResume 中回調取數據
@Override
public void onResume() {
super.onResume();
MainActivity.currFagTag = Constant.STR_FRAGMENT_CONTACTS;
// 從 Activity 取出上一個 Fragment,並判斷它是否實現了協議
Fragment f = ((MainActivity) getActivity()).getFragment(Constant.STR_FRAGMENT_MESSAGE);
if (f != null && f instanceof ContactFragmentCallBack) {
mContactFragmentCallBack = (ContactFragmentCallBack) f;
TextView textView = (TextView) ((MainActivity) getActivity())
.findViewById(R.id.contact_tv);
textView.setText(mContactFragmentCallBack.getContentStr());
}
}
這六點串起來,就是一個結構清晰、易於擴展的底部導航框架:位運算管狀態、onLayout 管自適應、代理模式管解耦、Fragment 事務管生命週期。比直接堆 if-else 和 findViewById 要優雅得多。
Android 屏幕適配實戰:多分辨率下的布局與圖片方案
對剛接觸 Android 的開發者來說,功能做完之後最大的挑戰往往不是邏輯,而是適配——同一份布局,在不同分辨率的機型上顯示效果千差萬別。 先學會查官方文檔 其實 An
Android HttpClient 使用詳解:GET、POST、檔案上傳與連線管理
Android 除了使用 java.net 相關 API,也可以透過 Apache HttpClient 完成 HTTP 請求。HttpClient 對 HTTP 協定支
Android 多選方塊對話框用法解析
多選方塊對話框概念 多選方塊對話框可讓使用者同時選擇多個項目,常用於興趣、通知設定或多條件篩選。 建立多選對話框 @Override protected Dialog o
Android 學習之路:ListView 的完整使用教學
學 Android 到第三天,最直觀的感受就是 ListView 幾乎無所不在——系統設定、通話記錄、簡訊列表,全是它。於是花了不少時間把它徹底摸了一遍。以下是個人的理解