Android 底部按鈕BottomNavigationView + Fragment + viewPager 的使用(一)

實現的效果,左右滑動,底部欄跟着滑動,中間加的是分幀的頁面java

      

上代碼:主頁面activity_main.xml android

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

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

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>

底部按鈕欄代碼:在menu 目錄下,navigation.xml   drawable 是圖片。就不貼上去了,隨便放個就行。app

<?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_black_24dp"
        android:title="@string/title_home" />

    <item
        android:id="@+id/navigation_dashboard"
        android:icon="@drawable/ic_dashboard_black_24dp"
        android:title="@string/title_dashboard" />

    <item
        android:id="@+id/navigation_notifications"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/title_notifications" />

    <item
        android:id="@+id/navigation_setting"
        android:icon="@drawable/ic_notifications_black_24dp"
        android:title="@string/title_notifications" />

</menu>

而後是分幀裏面的頁面:page1.xml  ,後面的複製前面的就好了 page2.xml  page3.xml  page4.xml ide

<?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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="frag1"
        android:textSize="30sp"/>

    <Button
        android:id="@+id/bt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment中的按鈕"
        android:textAllCaps="false"/>
</LinearLayout>

適配器代碼:MyFragAdaptre.javathis

package action.sun.com.freagment;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import java.util.List;

public class MyFragAdapter extends FragmentStatePagerAdapter {
    Context context;
    List<Fragment> listFragment;

    public MyFragAdapter(FragmentManager fm, Context context, List<Fragment> listFragment) {
        super(fm);
        this.context = context;
        this.listFragment = listFragment;
    }

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

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

分幀代碼:spa

Fragment1.java 後面的複製就行 Fragment2.java  Fragment3.java  Fragment4.java
package action.sun.com.freagment;

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;
import android.widget.Button;
import android.widget.Toast;

public class Fragment1 extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.page1, container, false);
        Button bt = (Button) view.findViewById(R.id.bt);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getActivity(), "Fragment1上的按鈕被點擊了", Toast.LENGTH_SHORT).show();
            }
        });
        return view;
    }
}

主頁面的顯示代碼:MainActivity.javacode

package action.sun.com.freagment;

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.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {

    private TextView mTextMessage;

    private static final String TAG = "MainActivity";
    ViewPager viewPager;
    BottomNavigationView navigation;//底部導航欄對象
    List<Fragment> listFragment;//存儲頁面對象


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

        initView();//初始化
    }


    private void initView() {
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        navigation = (BottomNavigationView) findViewById(R.id.navigation);

        //向ViewPager添加各頁面
        listFragment = new ArrayList<>();
        listFragment.add(new Fragment1());
        listFragment.add(new Fragment2());
        listFragment.add(new Fragment3());
        listFragment.add(new Fragment4());
        MyFragAdapter myAdapter = new MyFragAdapter(getSupportFragmentManager(), this, listFragment);
        viewPager.setAdapter(myAdapter);

        //導航欄點擊事件和ViewPager滑動事件,讓兩個控件相互關聯
        navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                //這裏設置爲:當點擊到某子項,ViewPager就滑動到對應位置
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        viewPager.setCurrentItem(0);
                        return true;
                    case R.id.navigation_dashboard:
                        viewPager.setCurrentItem(1);
                        return true;
                    case R.id.navigation_notifications:
                        viewPager.setCurrentItem(2);
                        return true;
                    case R.id.navigation_setting:
                        viewPager.setCurrentItem(3);
                        return true;
                    default:
                        break;
                }
                return false;
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //注意這個方法滑動時會調用屢次,下面是參數解釋:
                //position當前所處頁面索引,滑動調用的最後一次絕對是滑動中止所在頁面
                //positionOffset:表示從位置的頁面偏移的[0,1]的值。
                //positionOffsetPixels:以像素爲單位的值,表示與位置的偏移
            }

            @Override
            public void onPageSelected(int position) {
                //該方法只在滑動中止時調用,position滑動中止所在頁面位置
//                當滑動到某一位置,導航欄對應位置被按下
                navigation.getMenu().getItem(position).setChecked(true);
                //這裏使用navigation.setSelectedItemId(position);無效,
                //setSelectedItemId(position)的官網原句:Set the selected
                // menu item ID. This behaves the same as tapping on an item
                //未找到緣由
            }

            @Override
            public void onPageScrollStateChanged(int state) {
//這個方法在滑動是調用三次,分別對應下面三種狀態
// 這個方法對於發現用戶什麼時候開始拖動,
// 什麼時候尋呼機自動調整到當前頁面,或什麼時候徹底中止/空閒很是有用。
//                state表示新的滑動狀態,有三個值:
//                SCROLL_STATE_IDLE:開始滑動(空閒狀態->滑動),實際值爲0
//                SCROLL_STATE_DRAGGING:正在被拖動,實際值爲1
//                SCROLL_STATE_SETTLING:拖動結束,實際值爲2
            }
        });
    }
}

代碼完畢,運行就能夠看到效果了。xml

 

相關文章
相關標籤/搜索