Android商城開發系列(三)——使用Fragment+RadioButton實現商城底部導航欄

  在商城第一篇的開篇當中,咱們看到商城的效果圖裏面有一個底部導航欄效果,以下圖所示:java

  

  今天咱們就來實現商城底部導航欄,最終效果圖以下所示:android

  

  那麼這種效果是如何實現,實現的方式有不少種,最多見的就是使用Fragment+RadioButton去實現。下面咱們來寫一個例子緩存

  首先咱們先在activity_mian.xml定義佈局,整個佈局的外面是線性佈局,上面是幀佈局切換不一樣的Fragment,底下是RadioGroup嵌套的是RadioButton。代碼以下所示:app

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />


    <RadioGroup
        android:id="@+id/rg_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/home_bottom_parent_bg"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rb_home"
            style="@style/MainButtonStyle"
            android:drawableTop="@drawable/home_button_selector"
            android:text="首頁" />

        <RadioButton
            android:id="@+id/rb_type"
            style="@style/MainButtonStyle"
            android:drawableTop="@drawable/type_button_selector"
            android:text="分類" />

        <RadioButton
            android:id="@+id/rb_community"
            style="@style/MainButtonStyle"
            android:drawableTop="@drawable/community_button_selector"
            android:paddingTop="10dp"
            android:text="發現" />

        <RadioButton
            android:id="@+id/rb_cart"
            style="@style/MainButtonStyle"
            android:drawableTop="@drawable/cart_button_selector"
            android:text="購物車" />

        <RadioButton
            android:id="@+id/rb_user"
            style="@style/MainButtonStyle"
            android:drawableTop="@drawable/user_button_selector"
            android:text="我的中心" />
    </RadioGroup>


</LinearLayout>

  注意:上面還有樣式和drawable,下面咱們一個一個的來完善。ide

  首先來看樣式,打開【res】—【values】—【styles】,代碼以下所示:佈局

 <style name="MainButtonStyle">
        <!-- Customize your theme here. -->
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_weight">1</item>
        <item name="android:button">@null</item>
        <!--   <item name="android:drawablePadding">3dp</item>-->
        <item name="android:textColor">@drawable/bottom_button_text_selector</item>
        <item name="android:textSize">10sp</item>
        <item name="android:gravity">center</item>
    </style>

  裏面還有一個<item name="android:textColor">@drawable/bottom_button_text_selector</item>,這個是設置圖片和文字的顏色,在drawable的目錄下建bottom_button_text_selector,代碼以下所示:this

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color="#535353" android:state_checked="false"></item>
    <item android:color="#ff4040" android:state_checked="true"></item>


</selector>

  接着咱們繼續來完善drawable,有【首頁】【分類】【發現】【購物車】【我的中心】,寫法都是同樣的,這裏用【首頁】來作例子,在drawable目錄下建home_button_selector,代碼以下所示:spa

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/main_home" android:state_checked="false"></item>
    <item android:drawable="@drawable/main_home_press" android:state_checked="true"></item>

</selector>

   接下來看MainActivity中的代碼,代碼以下:3d

package com.nyl.shoppingmall.app.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;
import android.widget.RadioGroup;

import com.nyl.shoppingmall.R;
import com.nyl.shoppingmall.base.BaseFragment;
import com.nyl.shoppingmall.community.fragment.CommunityFragment;
import com.nyl.shoppingmall.home.fragment.HomeFragment;
import com.nyl.shoppingmall.shoppingcart.fragment.ShoppingCartFragment;
import com.nyl.shoppingmall.type.fragment.TypeCartFragment;
import com.nyl.shoppingmall.user.fragment.UserCartFragment;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends FragmentActivity{

    @Bind(R.id.frameLayout)
    FrameLayout frameLayout;
    @Bind(R.id.rg_main)
    RadioGroup rgMain;

    //裝fragment的實例集合
    private ArrayList<BaseFragment> fragments;

    private int position = 0;

    //緩存Fragment或上次顯示的Fragment
    private Fragment tempFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //ButterKnife和當前Activity綁定
        ButterKnife.bind(this);

        //初始化Fragment
        initFragment();
        //設置RadioGroup的監聽
        initListener();
    }

    private void initListener() {
        rgMain.check(R.id.rb_home);
        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.rb_home: //首頁
                        position = 0;
                        break;
                    case R.id.rb_type: //分類
                        position = 1;
                        break;
                    case R.id.rb_community: //發現
                        position = 2;
                        break;
                    case R.id.rb_cart: //購物車
                        position = 3;
                        break;
                    case R.id.rb_user: //我的中心
                        position = 4;
                        break;
                    default:
                        position = 0;
                        break;
                }
                //根據位置獲得相應的Fragment
                BaseFragment baseFragment = getFragment(position);
                /**
                 * 第一個參數: 上次顯示的Fragment
                 * 第二個參數: 當前正要顯示的Fragment
                 */
                switchFragment(tempFragment,baseFragment);
            }
        });
    }

    /**
     * 添加的時候按照順序
     */
    private void initFragment(){
        fragments = new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new TypeCartFragment());
        fragments.add(new CommunityFragment());
        fragments.add(new ShoppingCartFragment());
        fragments.add(new UserCartFragment());
    }

    /**
     * 根據位置獲得對應的 Fragment
     * @param position
     * @return
     */
    private BaseFragment getFragment(int position){
        if(fragments != null && fragments.size()>0){
            BaseFragment baseFragment = fragments.get(position);
            return baseFragment;
        }
        return null;
    }

    /**
     * 切換Fragment
     * @param fragment
     * @param nextFragment
     */
    private void switchFragment(Fragment fragment,BaseFragment nextFragment){
        if (tempFragment != nextFragment){
            tempFragment = nextFragment;
            if (nextFragment != null){
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                //判斷nextFragment是否添加成功
                if (!nextFragment.isAdded()){
                    //隱藏當前的Fragment
                    if (fragment != null){
                        transaction.hide(fragment);
                    }
                    //添加Fragment
                    transaction.add(R.id.frameLayout,nextFragment).commit();
                }else {
                    //隱藏當前Fragment
                    if (fragment != null){
                        transaction.hide(fragment);
                    }
                    transaction.show(nextFragment).commit();
                }
            }
        }
    }
}

  首先使用ButterKnife初始化佈局控件,而後在onCreate方法中初始化Fragment和綁定RadioGroup的選中改變事件,爲了方便初始化Fragment,寫了一個initFragment方法,在方法內部建立HomeFragment,TypeCartFragment,CommunityFragment,ShoppingCartFragment,UserCartFragment四個Fragment實例,而後使用一個fragments集合存儲這四個實例。接下來寫一個switchFragment方法,用於切換顯示指定的Fragmetn,當RadioGroup的選中改變時,首先根據選中的位置獲取到對應的Fragment,而後將獲取到的Fragment傳入到switchFragment方法中進行顯示。因爲每次RadioGroup的選中改變獲取到的Fragment都不同,從而能夠實現根據選中的RadioGroup展現不一樣的Fragment效果,也就是常見的Tab切換效果。code

  Activity中用到的HomeFragment,TypeCartFragment,CommunityFragment,ShoppingCartFragment,UserCartFragment這四個Fragment的代碼比較簡單,以HomeFragment爲例,代碼以下:

package com.nyl.shoppingmall.home.fragment;

import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.nyl.shoppingmall.base.BaseFragment;

/**
 * 首頁Fragment
 */
public class HomeFragment extends BaseFragment {

    private final static String TAG = HomeFragment.class.getSimpleName();

    private TextView textView;

    @Override
    public View initView() {
        textView = new TextView(mContext);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(25);
        Log.e(TAG,"主頁面的Fragment的UI被初始化了");
        return textView;
    }

    @Override
    public void initData() {
        super.initData();
        textView.setText("首頁");
        Log.e(TAG,"主頁面的Fragment的數據被初始化了");
    }
}
  HomeFragment繼承自BaseFragment,而後重寫父類的initView方法和initData方法,BaseFragment的代碼以下:
package com.nyl.shoppingmall.base;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * 基類Fragment
 * 首頁:HomeFragment
 * 分類:TypeFragment
 * 發現:CommunityFragment
 * 購物車:ShoppingCartFragment
 *  用戶中心:UserFragment
 *  等等都要繼承該類
 */

public abstract class BaseFragment extends Fragment{

    protected Context mContext;

    /**
     * 當該類被系統建立的時候回調
     * @param savedInstanceState
     */
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return initView();
    }

    //抽象類,由孩子實現,實現不一樣的效果
    public abstract View initView();

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    /**
     * 當子類須要聯網請求數據的時候,能夠重寫該方法,該方法中聯網請求
     */
    public void initData() {
    }
}

  其他幾個Fragment的代碼也相似,這裏就再也不細說了,使用Fragment+RadioButton實現底部導航欄的思路和代碼實現就是這樣的。

相關文章
相關標籤/搜索