現在的App主頁設計,一般采用的是幾個按鈕加上不同的Fragment切換。這樣看起來層次很清晰,功能明確,用戶一目了然。
實現這種效果的方法有很多種,網上第三方的庫也有很多很多。但是當我們使用第三方庫時,往往會受到它或多或少的限制,其實我們用原生的Android控件就可以實現這種效果,Google已經幫我們封裝得很好了。我使用的是RadioGroup加上Fragment的切換,話不多說,直接上代碼。
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="match_parent"
android:layout_height="@dimen/dp_44"
android:layout_margin="@dimen/dp_10"
android:orientation="horizontal"
android:weightSum="3">
<RadioButton
android:id="@+id/btn_product_barcode"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/putaway_operation_left_selector"
android:button="@null"
android:gravity="center"
android:text="@string/wms_col_product_barcode"
android:textColor="@drawable/putaway_operation_text_selector"/>
<RadioButton
android:id="@+id/btn_box"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/putaway_operation_middle_selector"
android:button="@null"
android:gravity="center"
android:text="@string/wms_col_container_no"
android:textColor="@drawable/putaway_operation_text_selector"/>
<RadioButton
android:id="@+id/btn_tray"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/putaway_operation_right_selector"
android:button="@null"
android:gravity="center"
android:text="@string/wms_col_pallet_id"
android:textColor="@drawable/putaway_operation_text_selector"/>
</RadioGroup>
<FrameLayout
android:id="@+id/fl_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
在布局文件中,上面是一個RadioGroup,里面有三個RadioButton,對應就是三個切換按鈕。下面的FrameLayout是切換的Fragment。
在Activity中,需要用代碼來實現Fragment的切換。必須先設置一個默認的Fragment,然后再根據RadioGroup的check事件來實現切換。
//設置默認選中的Fragment
mBtnProductBarcode.setChecked(true);
final FragmentManager fragmentManager = getSupportFragmentManager();
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.fl_content, new ProductBarcodeFragment());
transaction.commit();
//RadioGroup的check事件,來實現Fragment的切換
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
FragmentTransaction transaction = fragmentManager.beginTransaction();
//根據RadioButton不同的Id來選中不同的Fragment。
if (checkedId == R.id.btn_product_barcode) {
transaction.replace(R.id.fl_content, new ProductBarcodeFragment());
} else if (checkedId == R.id.btn_box) {
transaction.replace(R.id.fl_content, new BoxFragment());
} else if (checkedId == R.id.btn_tray) {
transaction.replace(R.id.fl_content, new TrayFragment());
}
transaction.commit();
}
});
接著我們可以在各自的Fragment中寫自己的布局和邏輯代碼,它們雖然都是掛載在一個Activity上面,但是它們互相之間并沒有什么影響。代碼很簡單,希望能幫到你。