1. 程式人生 > >Fragment建立新增切換和對應底部導航(三)

Fragment建立新增切換和對應底部導航(三)

目標:可以滑動Fragment來導航。

原來是通過FragmentManager新增Fragment後,show和hide來顯示和隱藏Fragment。

這裡使用Viewpager和FragmentPagerAdapter來實現。

 

把activity_main.xml中的FrameLayout改成ViewPager

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_weight="1"
        android:layout_width
="match_parent" android:layout_height="0dp"> </android.support.v4.view.ViewPager>

全部activity_main.xml檔案程式碼

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_weight="1" android:layout_width="match_parent" android:layout_height
="0dp"> </android.support.v4.view.ViewPager> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="55dp"> <View android:layout_width="wrap_content" android:layout_height="1dp" android:background="?android:listDivider" /> <LinearLayout android:layout_width="match_parent" android:orientation="horizontal" android:background="@android:color/white" android:layout_height="54dp"> <LinearLayout android:id="@+id/ll_home" android:layout_width="0dp" android:padding="4dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <ImageView android:id="@+id/iv_home" android:layout_width="28dp" android:layout_height="28dp" android:src="@drawable/bid02" tools:ignore="ContentDescription" /> <TextView android:id="@+id/tv_home" android:textColor="@color/home_back_unselected" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="首頁" android:layout_marginTop="2dp" android:textSize="14sp"/> </LinearLayout> <LinearLayout android:id="@+id/ll_invest" android:layout_width="0dp" android:padding="4dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <ImageView android:id="@+id/iv_invest" android:layout_width="28dp" android:layout_height="28dp" android:src="@drawable/bid04" /> <TextView android:id="@+id/tv_invest" android:textColor="@color/home_back_unselected" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="二頁" android:layout_marginTop="2dp" android:textSize="14sp"/> </LinearLayout> <LinearLayout android:id="@+id/ll_me" android:layout_width="0dp" android:padding="4dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <ImageView android:id="@+id/iv_me" android:layout_width="28dp" android:layout_height="28dp" android:src="@drawable/bid06" /> <TextView android:id="@+id/tv_me" android:textColor="@color/home_back_unselected" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="三頁" android:layout_marginTop="2dp" android:textSize="14sp"/> </LinearLayout>- <LinearLayout android:id="@+id/ll_more" android:layout_width="0dp" android:padding="4dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:orientation="vertical"> <ImageView android:id="@+id/iv_more" android:layout_width="28dp" android:layout_height="28dp" android:src="@drawable/bid08" /> <TextView android:id="@+id/tv_more" android:textColor="@color/home_back_unselected" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="四頁" android:layout_marginTop="2dp" android:textSize="14sp"/> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout>
View Code

 

 

在MainActivity中,獲取ViewPager物件

@BindView(R.id.viewPager)
ViewPager viewPager;

InitFragments函式去掉FragmentManager新增的程式碼,使用介面卡。

    private void InitFragments() {
        fragments.clear();

        if (fragmentA == null) {
            fragmentA = new FragmentA();
        }
        if (fragmentB == null) {
            fragmentB = new FragmentB();
        }
        if (fragmentC == null) {
            fragmentC = new FragmentC();
        }
        if (fragmentD == null) {
            fragmentD = new FragmentD();
        }
        fragments.add(fragmentA);
        fragments.add(fragmentB);
        fragments.add(fragmentC);
        fragments.add(fragmentD);

        TabPageAdapter adapter = new TabPageAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        //滑動響應介面實現
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectNavigation(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

 

介面卡類的程式碼

    class TabPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragments;
        public TabPageAdapter(FragmentManager fm,List<Fragment> fragments) {
            super(fm);
            this.fragments=fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }
    }

selectNavigaton也需要對切換Fragment,原來顯示和隱藏Fragment,現在不適用了,改成

viewPager.setCurrentItem(page,true);

MainActivity全部程式碼

package com.utopia.testfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends FragmentActivity {


    FragmentA fragmentA;
    FragmentB fragmentB;
    FragmentC fragmentC;
    FragmentD fragmentD;
    List<Fragment> fragments = new ArrayList<Fragment>();

    @BindView(R.id.iv_home)
    ImageView ivHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.ll_home)
    LinearLayout llHome;
    @BindView(R.id.iv_invest)
    ImageView ivInvest;
    @BindView(R.id.tv_invest)
    TextView tvInvest;
    @BindView(R.id.ll_invest)
    LinearLayout llInvest;
    @BindView(R.id.iv_me)
    ImageView ivMe;
    @BindView(R.id.tv_me)
    TextView tvMe;
    @BindView(R.id.ll_me)
    LinearLayout llMe;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.tv_more)
    TextView tvMore;
    @BindView(R.id.ll_more)
    LinearLayout llMore;
    @BindView(R.id.viewPager)
    ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        InitFragments();
        System.out.println("init DONE....................");
        selectNavigation(0);


    }

    @OnClick({R.id.ll_home, R.id.ll_invest, R.id.ll_me, R.id.ll_more})
    public void changeTab(View view) {
        switch (view.getId()) {
            case R.id.ll_home:
                selectNavigation(0);
                break;
            case R.id.ll_invest:
                selectNavigation(1);
                break;
            case R.id.ll_me:
                selectNavigation(2);
                break;
            case R.id.ll_more:
                selectNavigation(3);
                break;
        }
    }

    /***
     * 初始化:建立Fragment,新增到FrameLayout 中(R.id.content),並且新增到連結串列fragmetns中
     *
     */
    private void InitFragments() {
        fragments.clear();

        if (fragmentA == null) {
            fragmentA = new FragmentA();
        }
        if (fragmentB == null) {
            fragmentB = new FragmentB();
        }
        if (fragmentC == null) {
            fragmentC = new FragmentC();
        }
        if (fragmentD == null) {
            fragmentD = new FragmentD();
        }
        fragments.add(fragmentA);
        fragments.add(fragmentB);
        fragments.add(fragmentC);
        fragments.add(fragmentD);
//        for (Fragment frag : fragments) {
//            if (!frag.isAdded()) {
//                getSupportFragmentManager().beginTransaction().add(R.id.content, frag).commit();
//            }
//        }
        TabPageAdapter adapter = new TabPageAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        //滑動響應介面實現
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectNavigation(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void showFragment(int frag) {
        //首先隱藏所有Fragments
        for (Fragment f : fragments) {
            getSupportFragmentManager().beginTransaction().hide(f).commit();
        }
        //獲取當前 序號的fragment
        Fragment current_frag = fragments.get(frag);
        if (current_frag != null) {
            getSupportFragmentManager().beginTransaction().show(current_frag).commit();

        }

    }

    class TabPageAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragments;
        public TabPageAdapter(FragmentManager fm,List<Fragment> fragments) {
            super(fm);
            this.fragments=fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }
    }

    private void selectNavigation(int page) {
        //相關圖片,字型變成灰色
        ivHome.setImageResource(R.drawable.bid02);
        ivInvest.setImageResource(R.drawable.bid04);
        ivMe.setImageResource(R.drawable.bid06);
        ivMore.setImageResource(R.drawable.bid08);
        tvHome.setTextColor(getResources().getColor(R.color.home_back_unselected));
        tvInvest.setTextColor(getResources().getColor(R.color.home_back_unselected));
        tvMe.setTextColor(getResources().getColor(R.color.home_back_unselected));
        tvMore.setTextColor(getResources().getColor(R.color.home_back_unselected));


        switch (page) {
            case 0:
                ivHome.setImageResource(R.drawable.bid01);
                tvHome.setTextColor(getResources().getColor(R.color.home_back_selected_green));
                break;
            case 1:
                ivInvest.setImageResource(R.drawable.bid03);
                tvInvest.setTextColor(getResources().getColor(R.color.home_back_selected_green));
                break;
            case 2:
                ivMe.setImageResource(R.drawable.bid05);
                tvMe.setTextColor(getResources().getColor(R.color.home_back_selected_green));
                break;
            case 3:
                ivMore.setImageResource(R.drawable.bid07);
                tvMore.setTextColor(getResources().getColor(R.color.home_back_selected_green));
                break;
        }

        // 選擇導航的時候,同時選擇Fragment
        //showFragment(page);
        viewPager.setCurrentItem(page,true);
    }


}
MainActivity程式碼