Android使用底部导航2018-08-16

Android使用底部导航

Android 底部导航停留在屏幕底部,提供应用中顶级视图之间的导航。这是在具有向后兼容性的设计支持库中引入的。当应用程序有三到五个顶级导航时,应使用底部导航。

本文介绍了底部导航的基础知识,并将其与Fragments相结合。我们还将学习如何通过HTTP调用获取JSON 来加载带有网格数据的第一个片段(使用RecyclerView)。

下载代码下载.APK

1.底部导航

可以使用BottomNavigationView组件轻松添加底部导航。您必须使用引力或相对属性才能使其显示在屏幕底部。


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/frame_container"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>



        android:id="@+id/navigation"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_gravity="bottom"

        android:background="?android:attr/windowBackground"

        app:itemBackground="@color/bgBottomNavigation"

        android:foreground="?attr/selectableItemBackground"

        app:itemIconTint="@android:color/white"

        app:itemTextColor="@android:color/white"

        app:menu="@menu/navigation"/>


这里必须记下几个重要的属性。

app:menu - 用于显示导航项以及图标和文本的菜单资源文件。

app:itemBackground - 将背景颜色应用于底部导航。

app:itemTextColor - 底部导航项的文本颜色。

app:itemIconTint - 底部导航项的图标颜色。

何时使用底部导航?

根据设计规范,应根据标准使用以下导航。

导航抽屉 - 当顶级导航具有六个以上的目的地时使用。

标签 - 当有两个导航目的地时使用。

底部导航 - 当有五个顶级目的地时使用。

在进一步研究之前,请快速了解底部导航的设计规范。

Android使用底部导航2018-08-16_第1张图片

现在让我们通过在Android Studio中创建一个新项目来尝试它。

2.创建新项目

1。从File⇒NewProject在Android Studio中创建一个新项目,然后从模板中选择Basic Activity

2。下载此res文件夹并将drawable添加到项目的res。此文件夹包含底部导航项所需的必要绘图。

3。请确保您有设计支持库在你的build.gradle

的build.gradle

dependencies {

    implementation 'com.android.support:design:26.1.0'

}

4。将以下颜色,字符串值添加到colors.xmlstrings.xml中

colors.xml


    #7b4bff

    #6539ba

    #FF4081

    #fe485a

strings.xml中

    Bottom Navigation

    Shop

    Gifts

    Cart

    Profile

5。当使用菜单文件呈现底部导航项时,在res⇒菜单文件夹下创建一个名为navigation.xml的新xml 。

navigation.xml


http://schemas.android.com/apk/res/android">



        android:id="@+id/navigation_shop"

        android:icon="@drawable/ic_store_white_24dp"

        android:title="@string/title_shop"/>



        android:id="@+id/navigation_gifts"

        android:icon="@drawable/ic_card_giftcard_white_24dp"

        android:title="@string/title_gifts"/>



        android:id="@+id/navigation_cart"

        android:icon="@drawable/ic_shopping_cart_white_24dp"

        android:title="@string/title_cart"/>



        android:id="@+id/navigation_profile"

        android:icon="@drawable/ic_person_white_24dp"

        android:title="@string/title_profile"/>


6。打开主要活动的布局文件,即activity_main.xml,并添加BottomNavigationView小部件。这里我们还添加了一个FrameLayout来在选择导航项时加载Fragments

activity_main.xml中


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"

    tools:context="info.androidhive.bottomnavigation.MainActivity">



        android:id="@+id/frame_container"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>



        android:id="@+id/navigation"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_gravity="bottom"

        android:background="?android:attr/windowBackground"

        app:itemBackground="@color/bgBottomNavigation"

        android:foreground="?attr/selectableItemBackground"

        app:itemIconTint="@android:color/white"

        app:itemTextColor="@android:color/white"

        app:menu="@menu/navigation"/>


7。现在打开MainActivity.java并按如下所示进行修改。

>此处,选择底部导航项时将调用OnNavigationItemSelectedListener。现在我们只是在选择导航项时更改工具栏标题。

MainActivity.java

packageinfo.androidhive.bottomnavigation;


importandroid.os.Bundle;

importandroid.support.annotation.NonNull;

importandroid.support.design.widget.BottomNavigationView;

importandroid.support.design.widget.CoordinatorLayout;

importandroid.support.v4.app.Fragment;

importandroid.support.v4.app.FragmentTransaction;

importandroid.support.v7.app.ActionBar;

importandroid.support.v7.app.AppCompatActivity;

importandroid.view.MenuItem;


importinfo.androidhive.bottomnavigation.fragment.CartFragment;

importinfo.androidhive.bottomnavigation.fragment.GiftsFragment;

importinfo.androidhive.bottomnavigation.fragment.ProfileFragment;

importinfo.androidhive.bottomnavigation.fragment.StoreFragment;

importinfo.androidhive.bottomnavigation.helper.BottomNavigationBehavior;


publicclassMainActivity extendsAppCompatActivity {


    privateActionBar toolbar;


    @Override

    protectedvoidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        toolbar = getSupportActionBar();


        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);


        toolbar.setTitle("Shop");

    }


    privateBottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener

            = newBottomNavigationView.OnNavigationItemSelectedListener() {


        @Override

        publicbooleanonNavigationItemSelected(@NonNullMenuItem item) {

            Fragment fragment;

            switch(item.getItemId()) {

                caseR.id.navigation_shop:

                    toolbar.setTitle("Shop");

                    returntrue;

                caseR.id.navigation_gifts:

                    toolbar.setTitle("My Gifts");

                    returntrue;

                caseR.id.navigation_cart:

                    toolbar.setTitle("Cart");

                    returntrue;

                caseR.id.navigation_profile:

                    toolbar.setTitle("Profile");

                    returntrue;

            }

            returnfalse;

        }

    };

}

如果您运行该应用程序,则可以看到显示的底部导航,如下所示。

Android使用底部导航2018-08-16_第2张图片

3.添加片段

当我们准备好底部导航时,让我们看看如何在选择导航菜单项时切换视图。这可以通过使用片段轻松完成。

注意:根据设计规范使用底部导航时不应使用ViewPager(避免使用横向运动在视图之间转换)

我创建一个名为四个片段StoreFragmentGiftsFragmentCartFragmentProfileFragment

8。通过转到文件⇒新⇒片段⇒片段(空白)创建新片段并将其命名为StoreFragment.java。同样也要创建其他三个片段。

9。打开MainActivity.java并修改底部导航侦听器,如下所示,以在FrameLayout中加载片段。

loadFragment() - 将Fragment加载到FrameLayout中。通过传递适当的片段实例,在OnNavigationItemSelectedListener回调中调用相同的方法。

>特定模块所需的逻辑进入适当的片段,保持MainActivity清洁。

MainActivity.java

packageinfo.androidhive.bottomnavigation;


importandroid.os.Bundle;

importandroid.support.annotation.NonNull;

importandroid.support.design.widget.BottomNavigationView;

importandroid.support.design.widget.CoordinatorLayout;

importandroid.support.v4.app.Fragment;

importandroid.support.v4.app.FragmentTransaction;

importandroid.support.v7.app.ActionBar;

importandroid.support.v7.app.AppCompatActivity;

importandroid.view.MenuItem;


importinfo.androidhive.bottomnavigation.fragment.CartFragment;

importinfo.androidhive.bottomnavigation.fragment.GiftsFragment;

importinfo.androidhive.bottomnavigation.fragment.ProfileFragment;

importinfo.androidhive.bottomnavigation.fragment.StoreFragment;

importinfo.androidhive.bottomnavigation.helper.BottomNavigationBehavior;


publicclassMainActivity extendsAppCompatActivity {


    privateActionBar toolbar;


    @Override

    protectedvoidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        toolbar = getSupportActionBar();


        // load the store fragment by default

        toolbar.setTitle("Shop");

        loadFragment(newStoreFragment());

    }


    privateBottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener

            = newBottomNavigationView.OnNavigationItemSelectedListener() {


        @Override

        publicbooleanonNavigationItemSelected(@NonNullMenuItem item) {

            Fragment fragment;

            switch(item.getItemId()) {

                caseR.id.navigation_shop:

                    toolbar.setTitle("Shop");

                    fragment = newStoreFragment();

                    loadFragment(fragment);

                    returntrue;

                caseR.id.navigation_gifts:

                    toolbar.setTitle("My Gifts");

                    fragment = newGiftsFragment();

                    loadFragment(fragment);

                    returntrue;

                caseR.id.navigation_cart:

                    toolbar.setTitle("Cart");

                    fragment = newCartFragment();

                    loadFragment(fragment);

                    returntrue;

                caseR.id.navigation_profile:

                    toolbar.setTitle("Profile");

                    fragment = newProfileFragment();

                    loadFragment(fragment);

                    returntrue;

            }


            returnfalse;

        }

    };


    privatevoidloadFragment(Fragment fragment) {

        // load fragment

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        transaction.replace(R.id.frame_container, fragment);

        transaction.addToBackStack(null);

        transaction.commit();

    }


}

现在,如果您运行项目,则可以在选择导航时看到加载的片段。

Android使用底部导航2018-08-16_第3张图片

4.实现ShopFragment - 在网格中显示项目

现在我们将看到如何实现第一个片段,即ShopFragment,它以网格方式显示商店项目。为了演示,我创建了一个样本json,其中包含很少的待售电影。要实现这一点,我们所要做的就是获取json并以网格格式在RecyclerView中显示数据。为了使任务更简单,请按照我的另一篇解释相同的文章。

https://api.androidhive.info/json/movies_2017.json

10。打开build.gradle并添加RecyclerView,CardView,Volley和Glide依赖项。

的build.gradle

dependencies {

    // RecyclerView

    compile 'com.android.support:recyclerview-v7:26.1.0'


    // CardView

    compile 'com.android.support:cardview-v7:26.1.0'


    // volley http library

    implementation 'com.android.volley:volley:1.0.0'

    implementation 'com.google.code.gson:gson:2.6.2'


    // glide image library

    implementation 'com.github.bumptech.glide:glide:4.3.1'

}

11。创建一个名为MyApplication.java的类,从Application实现该类。这是一个单例类,其中将启动齐射库。

MyApplication.java

packageinfo.androidhive.bottomnavigation.app;


importandroid.app.Application;

importandroid.text.TextUtils;


importcom.android.volley.Request;

importcom.android.volley.RequestQueue;

importcom.android.volley.toolbox.Volley;


publicclassMyApplication extendsApplication {


    publicstaticfinalString TAG = MyApplication.class

            .getSimpleName();


    privateRequestQueue mRequestQueue;


    privatestaticMyApplication mInstance;


    @Override

    publicvoidonCreate() {

        super.onCreate();

        mInstance = this;

    }


    publicstaticsynchronizedMyApplication getInstance() {

        returnmInstance;

    }


    publicRequestQueue getRequestQueue() {

        if(mRequestQueue == null) {

            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

        }


        returnmRequestQueue;

    }


    public voidaddToRequestQueue(Request req, String tag) {

        // set the default tag if tag is empty

        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        getRequestQueue().add(req);

    }


    public voidaddToRequestQueue(Request req) {

        req.setTag(TAG);

        getRequestQueue().add(req);

    }


    publicvoidcancelPendingRequests(Object tag) {

        if(mRequestQueue != null) {

            mRequestQueue.cancelAll(tag);

        }

    }

}

12。打开AndroidManifest.xml并将MyApplication添加到标记。我们还需要INTERNET权限才能进行http调用。

AndroidManifest.xml中


http://schemas.android.com/apk/res/android"

    package="info.androidhive.bottomnavigation">


    



        android:name=".app.MyApplication"

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">


            android:name=".MainActivity"

            android:label="@string/app_name">

            

                


                




13。打开StoreFragment的布局文件,即fragment_store.xml,并添加下面的布局代码。这里我们添加了RecyclerView组件。

fragment_store.xml

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:background="#f1f5f7"

    tools:context="info.androidhive.bottomnavigation.fragment.StoreFragment">



        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:orientation="vertical">



            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:paddingLeft="@dimen/activity_horizontal_margin"

            android:paddingTop="10dp"

            android:text="New Release Films"

            android:textColor="#111"

            android:textSize="16dp"/>



            android:id="@+id/recycler_view"

            android:layout_width="match_parent"

            android:layout_height="wrap_content"

            android:clipToPadding="false"

            android:scrollbars="vertical"/>


14。在res⇒布局下创建名为store_item_row.xml的xml 布局。此布局文件将在RecyclerView适配器类中用于呈现单个项目。

store_item_row.xml

http://schemas.android.com/apk/res/android"

    xmlns:card_view="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="wrap_content">



        android:id="@+id/card_view"

        android:layout_width="match_parent"

        android:layout_height="match_parent"

        android:layout_gravity="center"

        android:layout_margin="@dimen/card_margin"

        android:clickable="true"

        android:elevation="3dp"

        android:foreground="?attr/selectableItemBackground"

        card_view:cardCornerRadius="@dimen/card_album_radius">



            android:layout_width="match_parent"

            android:layout_height="match_parent">



                android:id="@+id/thumbnail"

                android:layout_width="match_parent"

                android:layout_height="@dimen/album_cover_height"

                android:background="?attr/selectableItemBackgroundBorderless"

                android:clickable="true"

                android:scaleType="fitXY"/>



                android:id="@+id/title"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:layout_below="@id/thumbnail"

                android:lines="2"

                android:paddingLeft="@dimen/album_title_padding"

                android:paddingRight="@dimen/album_title_padding"

                android:paddingTop="@dimen/album_title_padding"

                android:textColor="#111"

                android:textSize="11dp"/>



                android:id="@+id/price"

                android:layout_width="match_parent"

                android:layout_height="wrap_content"

                android:layout_below="@id/title"

                android:layout_marginRight="10dp"

                android:gravity="right"

                android:paddingBottom="@dimen/songs_count_padding_bottom"

                android:textColor="@color/colorAccent"

                android:textSize="11dp"/>





15。创建一个名为Movie.java的类。解析json时,此POJO类将非常有用。

Movie.java

packageinfo.androidhive.bottomnavigation;


publicclassMovie {

    String title;

    String image;

    String price;


    publicString getTitle() {

        returntitle;

    }


    publicvoidsetTitle(String title) {

        this.title = title;

    }


    publicString getImage() {

        returnimage;

    }


    publicvoidsetImage(String image) {

        this.image = image;

    }


    publicString getPrice() {

        returnprice;

    }


    publicvoidsetPrice(String price) {

        this.price = price;

    }

}

16。现在打开StoreFragment.java并添加下面的代码。为简单起见,RecyclerView适配器类StoreAdapter包含在同一个片段中。

fetchStoreItems()方法使用Volley获取电影json并使用Gson对其进行序列化。

StoreAdapter类在RecyclerView中呈现电影。

StoreFragment.java

packageinfo.androidhive.bottomnavigation.fragment;



importandroid.content.Context;

importandroid.content.res.Resources;

importandroid.graphics.Rect;

importandroid.os.Bundle;

importandroid.support.v4.app.Fragment;

importandroid.support.v7.widget.DefaultItemAnimator;

importandroid.support.v7.widget.GridLayoutManager;

importandroid.support.v7.widget.RecyclerView;

importandroid.util.Log;

importandroid.util.TypedValue;

importandroid.view.LayoutInflater;

importandroid.view.View;

importandroid.view.ViewGroup;

importandroid.widget.ImageView;

importandroid.widget.TextView;

importandroid.widget.Toast;


importcom.android.volley.Response;

importcom.android.volley.VolleyError;

importcom.android.volley.toolbox.JsonArrayRequest;

importcom.bumptech.glide.Glide;

importcom.google.gson.Gson;

importcom.google.gson.reflect.TypeToken;


importorg.json.JSONArray;


importjava.util.ArrayList;

importjava.util.List;


importinfo.androidhive.bottomnavigation.Movie;

importinfo.androidhive.bottomnavigation.app.MyApplication;

importinfo.androidhive.bottomnavigation.R;


publicclassStoreFragment extendsFragment {


    privatestaticfinalString TAG = StoreFragment.class.getSimpleName();

    privatestaticfinalString URL = "https://api.androidhive.info/json/movies_2017.json";


    privateRecyclerView recyclerView;

    privateList movieList;

    privateStoreAdapter mAdapter;


    publicStoreFragment() {

        // Required empty public constructor

    }


    publicstaticStoreFragment newInstance(String param1, String param2) {

        StoreFragment fragment = newStoreFragment();

        Bundle args = newBundle();

        fragment.setArguments(args);

        returnfragment;

    }


    @Override

    publicvoidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

    }


    @Override

    publicView onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

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


        recyclerView = view.findViewById(R.id.recycler_view);

        movieList = newArrayList<>();

        mAdapter = newStoreAdapter(getActivity(), movieList);


        RecyclerView.LayoutManager mLayoutManager = newGridLayoutManager(getActivity(), 3);

        recyclerView.setLayoutManager(mLayoutManager);

        recyclerView.addItemDecoration(newGridSpacingItemDecoration(2, dpToPx(8), true));

        recyclerView.setItemAnimator(newDefaultItemAnimator());

        recyclerView.setAdapter(mAdapter);

        recyclerView.setNestedScrollingEnabled(false);


        fetchStoreItems();


        returnview;

    }


    privatevoidfetchStoreItems() {

        JsonArrayRequest request = newJsonArrayRequest(URL,

                newResponse.Listener() {

                    @Override

                    publicvoidonResponse(JSONArray response) {

                        if(response == null) {

                            Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();

                            return;

                        }


                        List items = newGson().fromJson(response.toString(), newTypeToken>() {

                        }.getType());


                        movieList.clear();

                        movieList.addAll(items);


                        // refreshing recycler view

                        mAdapter.notifyDataSetChanged();

                    }

                }, newResponse.ErrorListener() {

            @Override

            publicvoidonErrorResponse(VolleyError error) {

                // error in getting json

                Log.e(TAG, "Error: "+ error.getMessage());

                Toast.makeText(getActivity(), "Error: "+ error.getMessage(), Toast.LENGTH_SHORT).show();

            }

        });


        MyApplication.getInstance().addToRequestQueue(request);

    }


    publicclassGridSpacingItemDecoration extendsRecyclerView.ItemDecoration {


        privateintspanCount;

        privateintspacing;

        privatebooleanincludeEdge;


        publicGridSpacingItemDecoration(intspanCount, intspacing, booleanincludeEdge) {

            this.spanCount = spanCount;

            this.spacing = spacing;

            this.includeEdge = includeEdge;

        }


        @Override

        publicvoidgetItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

            intposition = parent.getChildAdapterPosition(view); // item position

            intcolumn = position % spanCount; // item column


            if(includeEdge) {

                outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)

                outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)


                if(position < spanCount) { // top edge

                    outRect.top = spacing;

                }

                outRect.bottom = spacing; // item bottom

            } else{

                outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)

                outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)

                if(position >= spanCount) {

                    outRect.top = spacing; // item top

                }

            }

        }

    }


    /**

     * Converting dp to pixel

     */

    privateintdpToPx(intdp) {

        Resources r = getResources();

        returnMath.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));

    }


    classStoreAdapter extendsRecyclerView.Adapter {

        privateContext context;

        privateList movieList;


        publicclassMyViewHolder extendsRecyclerView.ViewHolder {

            publicTextView name, price;

            publicImageView thumbnail;


            publicMyViewHolder(View view) {

                super(view);

                name = view.findViewById(R.id.title);

                price = view.findViewById(R.id.price);

                thumbnail = view.findViewById(R.id.thumbnail);

            }

        }



        publicStoreAdapter(Context context, List movieList) {

            this.context = context;

            this.movieList = movieList;

        }


        @Override

        publicMyViewHolder onCreateViewHolder(ViewGroup parent, intviewType) {

            View itemView = LayoutInflater.from(parent.getContext())

                    .inflate(R.layout.store_item_row, parent, false);


            returnnewMyViewHolder(itemView);

        }


        @Override

        publicvoidonBindViewHolder(MyViewHolder holder, finalintposition) {

            finalMovie movie = movieList.get(position);

            holder.name.setText(movie.getTitle());

            holder.price.setText(movie.getPrice());


            Glide.with(context)

                    .load(movie.getImage())

                    .into(holder.thumbnail);

        }


        @Override

        publicintgetItemCount() {

            returnmovieList.size();

        }

    }

}

现在,如果您运行该应用程序,您可以看到ShopFragment以网格方式显示电影。同样,您也可以实现其他片段。

Android使用底部导航2018-08-16_第4张图片

5.在滚动条上隐藏底部导航

根据设计规范,滚动内容时必须隐藏底部导航,从而为屏幕上的内容提供更多空间。为此,我们需要将BottomNavigationBehavior附加到底部导航。

17。使用以下代码创建名为BottomNavigationBehavior.java的类。

BottomNavigationBehavior.java

packageinfo.androidhive.bottomnavigation.helper;


importandroid.content.Context;

importandroid.support.design.widget.BottomNavigationView;

importandroid.support.design.widget.CoordinatorLayout;

importandroid.support.v4.view.ViewCompat;

importandroid.util.AttributeSet;

importandroid.view.View;

importandroid.widget.FrameLayout;


publicclassBottomNavigationBehavior extendsCoordinatorLayout.Behavior {


    publicBottomNavigationBehavior() {

        super();

    }


    publicBottomNavigationBehavior(Context context, AttributeSet attrs) {

        super(context, attrs);

    }


    @Override

    publicbooleanlayoutDependsOn(CoordinatorLayout parent, BottomNavigationView child, View dependency) {

        booleandependsOn = dependency instanceofFrameLayout;

        returndependsOn;

    }


    @Override

    publicbooleanonStartNestedScroll(CoordinatorLayout coordinatorLayout, BottomNavigationView child, View directTargetChild, View target, intnestedScrollAxes) {

        returnnestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL;

    }


    @Override

    publicvoidonNestedPreScroll(CoordinatorLayout coordinatorLayout, BottomNavigationView child, View target, intdx, intdy, int[] consumed) {

        if(dy < 0) {

            showBottomNavigationView(child);

        } elseif(dy > 0) {

            hideBottomNavigationView(child);

        }

    }


    privatevoidhideBottomNavigationView(BottomNavigationView view) {

        view.animate().translationY(view.getHeight());

    }


    privatevoidshowBottomNavigationView(BottomNavigationView view) {

        view.animate().translationY(0);

    }

}

18。添加BottomNavigationBehavior使用setBehavior()MainActivity.java如下所示。

MainActivity.java

publicclassMainActivity extendsAppCompatActivity {


    privateActionBar toolbar;


    @Override

    protectedvoidonCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);


        // attaching bottom sheet behaviour - hide / show on scroll

        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) navigation.getLayoutParams();

        layoutParams.setBehavior(newBottomNavigationBehavior());


        // load the store fragment by default

        // ..

    }

}

现在,如果您测试应用程序,则可以在滚动应用程序内容时看到底部导航向下滑动。

Android使用底部导航2018-08-16_第5张图片

你可能感兴趣的:(Android使用底部导航2018-08-16)