Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

仿 QQ 主界面框架源碼改進筆記:Fragment 組合的六個要點

編輯:關於 Android 程式設計

本文基於 CSDN 上一位前輩的經典文章改進而來。原作者的面向對象設計思路非常清晰,值得細讀。以下是我在學習過程中整理出的幾個可借鑑之處。

一、用位運算代替 switch 做標識判斷

把每個 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);
}

二、在 onLayout 中動態調整中間按鈕間距

底部欄中間那兩個按鈕要和兩側均勻分佈,硬編碼 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);
    }
}

五、Fragment 事務的創建時機

原來的 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);
    }
}

六、Fragment 之間跳轉並傳值

場景:在 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 要優雅得多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved