1. 程式人生 > >Android 底部按鈕BottomNavigationView + Fragment + viewPager 的使用(一)

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

activit osi PE star context XML ppc getitemid 對象

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

技術分享圖片 技術分享圖片

上代碼:主頁面activity_main.xml

<?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 是圖片。就不貼上去了,隨便放個就行。

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

<?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.java

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();
    }
 }

分幀代碼:

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.java

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
            }
        });
    }
}

代碼完畢,運行就可以看到效果了。

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