BottomNavigationView+Fragments

原文傳送門
記錄一個Google官方BottomNavigationView組件+Fragments的布局。

新建帶有BottomNavigationView的Activity

首先,新建一個帶有BottomNavigationView的Activity,這里可以新建一個空白的Activity然后在布局文件中添加BottomNavigationView,也可以直接新建一個Bottom BottomNavigation Activity,這樣就自動給添加好了.布局文件activity_main.xml如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/navigation" />
</LinearLayout>

BottomNavigationView中的三個圖文按鈕寫在res/menu下:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/navigation_home"
        android:icon="@drawable/ic_home"
        android:title="Home" />
    <item
        android:id="@+id/navigation_favourite"
        android:icon="@drawable/ic_favorite"
        android:title="Favourite" />
    <item
        android:id="@+id/navigation_profile"
        android:icon="@drawable/ic_person"
        android:title="Profile" />
</menu>

這里可能會因為com.android.support:design包的版本問題會讓APP掛掉,此次demo中的build.gradle部分配置如下:

//這里只展示部分配置
android {
    compileSdkVersion 25
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 25
      }
}

  dependencies {
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-vector-drawable:25.3.1'
}

效果如下:

效果圖1

其中圖文按鈕的點亮狀態的顏色是當前Activity主題配置文件中的

<item name="colorPrimary">@color/themecolor</item>

新建Fragment

新建三個Fragment:HomeFragment、FavouriteFragment、ProfileFragment,以及對應的布局文件fragment_home.xml、fragment_favourite.xml、fragment_profile.xml.

新建的Fragment中要注意的問題是在onCreateView中inflate布局文件時,要寫成:

View view = inflater.inflate(R.layout.fragment_home, container, false);

或者

View view = inflater.inflate(R.layout.fragment_home, null);

不能寫成

View view = inflater.inflate(R.layout.fragment_home, container);

否則會報錯:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

具體原因可參考這里.

三個Fragment的布局文件都是簡單的一個居中的TextView,分別顯示Home、Favorite、Profile以示區別.

聯動BottomNavigationView

接下來就是在MainActivity中寫相關的聯動邏輯了

選擇顯示哪一個Fragment,其他的隱藏:

    //顯示
    private void showFragment(int index) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragment(transaction);
        switch (index) {
            case FRAGMENT_HOME:
                if (mFragmentHome == null) {
                    mFragmentHome = new HomeFragment();
                    transaction.add(R.id.content, mFragmentHome);
                } else {
                    transaction.show(mFragmentHome);
                }
                break;
            case FRAGMENT_FAVOURITE:
                if (mFragmentFavourite == null) {
                    mFragmentFavourite = new FavouriteFragment();
                    transaction.add(R.id.content, mFragmentFavourite);
                } else {
                    transaction.show(mFragmentFavourite);
                }
                break;
            case FRAGMENT_PROFILE:
                if (mFragmentProfile == null) {
                    mFragmentProfile = new ProfileFragment();
                    transaction.add(R.id.content, mFragmentProfile);
                } else {
                    transaction.show(mFragmentProfile);

                }
                break;
        }
        transaction.commit();
    }

    //隱藏
    private void hideFragment(FragmentTransaction transaction) {
        if (mFragmentHome != null) {
            transaction.hide(mFragmentHome);
        }
        if (mFragmentFavourite != null) {
            transaction.hide(mFragmentFavourite);
        }
        if (mFragmentProfile != null) {
            transaction.hide(mFragmentProfile);
        }
    }

最后在OnNavigationItemSelectedListener中寫點擊對應item時聯動Fragment的邏輯:


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    showFragment(FRAGMENT_HOME);
                    return true;
                case R.id.navigation_favourite:
                    showFragment(FRAGMENT_FAVOURITE);
                    return true;
                case R.id.navigation_profile:
                    showFragment(FRAGMENT_PROFILE);
                    return true;
            }
            return false;
        }

    };

大功告成,最終效果如下:


效果圖2

MainActivity.java完整代碼:

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
    private static final int FRAGMENT_HOME = 0;
    private static final int FRAGMENT_FAVOURITE = 1;
    private static final int FRAGMENT_PROFILE = 2;

    private Fragment mFragmentHome;
    private Fragment mFragmentFavourite;
    private Fragment mFragmentProfile;
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    showFragment(FRAGMENT_HOME);
                    return true;
                case R.id.navigation_favourite:
                    showFragment(FRAGMENT_FAVOURITE);
                    return true;
                case R.id.navigation_profile:
                    showFragment(FRAGMENT_PROFILE);
                    return true;
            }
            return false;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        //默認顯示HomeFragment
        showFragment(FRAGMENT_HOME);
    }

    private void showFragment(int index) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        hideFragment(transaction);
        switch (index) {
            case FRAGMENT_HOME:
                if (mFragmentHome == null) {
                    mFragmentHome = new HomeFragment();
                    transaction.add(R.id.content, mFragmentHome);
                } else {
                    transaction.show(mFragmentHome);
                }
                break;
            case FRAGMENT_FAVOURITE:
                if (mFragmentFavourite == null) {
                    mFragmentFavourite = new FavouriteFragment();
                    transaction.add(R.id.content, mFragmentFavourite);
                } else {
                    transaction.show(mFragmentFavourite);
                }
                break;
            case FRAGMENT_PROFILE:
                if (mFragmentProfile == null) {
                    mFragmentProfile = new ProfileFragment();
                    transaction.add(R.id.content, mFragmentProfile);
                } else {
                    transaction.show(mFragmentProfile);

                }
                break;
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (mFragmentHome != null) {
            transaction.hide(mFragmentHome);
        }
        if (mFragmentFavourite != null) {
            transaction.hide(mFragmentFavourite);
        }
        if (mFragmentProfile != null) {
            transaction.hide(mFragmentProfile);
        }
    }
}

HomeFragment.java完整代碼如下,其余類似:

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;

/**
 * Created by lcgao on 2017/12/27.
 */

public class HomeFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,460評論 25 708
  • 前言 Fragment想必大家不陌生吧,在日常開發中,對于Fragment的使用也很頻繁,現在主流的APP中,基本...
    斜杠時光閱讀 2,594評論 4 22
  • Fragment的應用真的是越來越廣泛了,之前Android在3.0版本加入Fragment的時候,主要是為了解決...
    閑庭閱讀 2,938評論 0 10
  • 在一片森林中存在著一個熊的國度,它們全是一身棕色皮毛,過著平和半人類式的生活。然而在數十個棕熊家族其中的一個家族里...
    道亦然閱讀 543評論 0 0
  • (01) 大二的第二個學期,在宿舍玩了一個學期的我突然發覺是要出去見見點世面,順便掙點下學期的生活費。 承蒙朋友介...
    愛吃西瓜的小伙閱讀 339評論 4 0