安卓 BottomNavigationBar + ViewPager + Fragment应用(34)

总的效果就是一个可以滑动切换BottomNavigationBar的视图,其中每次切换的为Fragment。

首先我们需要设计fragment的视图,接着实现一个Fragment的逻辑功能,这里的代码就略过了(就是实现几个Fragment)。

然后我们实现一个Activity的布局来承载BottomNavigationBar + ViewPager + Fragment:

<?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"
    android:orientation="vertical">

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

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="@color/colorPrimary"/>

    <com.ashokvarma.bottomnavigation.BottomNavigationBar
        android:id="@+id/bottom_navigation_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

对于ViewPager,我们需要重写一个适配器。在这里,由于其中放入的是fragment,所以我们要继承自FragmentPagerAdapter这个类:

public class MyPagerAdapter extends FragmentPagerAdapter {

    private FragmentManager fragmentManager;
    private List<Fragment> fragments;

    //这里传入的是一个FragmentManger以及一个Fragment的列表,也就是所有需要的Fragment都放入这个队列中。
    public MyPagerAdapter(FragmentManager fm, List<Fragment> mFragments) {
        super(fm);
        this.fragments = mFragments;
        this.fragmentManager = fm;
    }

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

    @Override
    public int getCount() {
        return fragments.size();
    }
}
之后我们在Activity实现以下逻辑:
public class NiuBiJieMianMainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private List<Fragment> fragmentList;
    private BottomNavigationBar bottomNavigationBar;

    private final String ONE = "one";
    private final String TWO = "two";
    private final String THREE = "three";

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

        bottomNavigationBar = findViewById(R.id.bottom_navigation_bar);

        viewPager = findViewById(R.id.viewpager_one);
        //将所有的fragment放入一个ArrayList中
        fragmentList = new ArrayList<Fragment>();
        Fragment f1 = new FirstFragment();
        Fragment f2 = new SecondFragment();
        Fragment f3 = new ThirdFragment();
        fragmentList.add(f1);
        fragmentList.add(f2);
        fragmentList.add(f3);
        FragmentManager fragmentManager = getSupportFragmentManager();
        MyPagerAdapter myPagerAdapter = new MyPagerAdapter(fragmentManager, fragmentList);

        //将viewPager设置Adapter
        viewPager.setAdapter(myPagerAdapter);
        //设置初始化的位置(即第0个位置,开始的位置)
        viewPager.setCurrentItem(0);
        //当做出动作时,通过此监听
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //滑动页面之后做的事,这里与BottomNavigationBar连接,设置BottomNavigationBar。这是我们可以通过滑动改变BottomNavigationBar
                bottomNavigationBar.selectTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        bottomNavigationBar
                .setInActiveColor(R.color.colorPrimary) //未选中状态颜色
                .setActiveColor(R.color.colorAccent)  //选中状态颜色
                .setMode(BottomNavigationBar.MODE_FIXED) //导航栏模式
                .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC) //导航栏背景模式(图标的动画样式和这个有关系 变大了)
                .addItem(new BottomNavigationItem(R.drawable.bottom_1, "first"/*选中的图片样式以及文字*/).setInactiveIconResource(R.drawable.ic_launcher_background)/*未选中时样式*/)
                .addItem(new BottomNavigationItem(R.drawable.bottom_2, "second").setInactiveIconResource(R.drawable.ic_launcher_background))
                .addItem(new BottomNavigationItem(R.drawable.bottom_3, "third").setInactiveIconResource(R.drawable.ic_launcher_background))
                .setFirstSelectedPosition(0)//初始化之后第一个选中的位置
                .initialise();

        //当对BottomNavigationBar进行操作时,通过下列函数监听。
        bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position) {
                //被选中时,改变viewPager中的位置进而得到fragment的数据,即改变fragment。
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabUnselected(int position) {

            }

            @Override
            public void onTabReselected(int position) {

            }
        });
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android TableLayout is a ViewGroup which displays the data in a tabular form. It is used to create a user interface with rows and columns similar to a spreadsheet. ViewPager is a View which allows the user to swipe left and right to navigate between pages. Fragments are reusable components which can be used to create dynamic user interfaces. To create a TableLayout with ViewPager and Fragment, follow the below steps: 1. Create a new Android Studio project. 2. Add the required dependencies in the build.gradle file. 3. Create a new Fragment class for each tab. 4. Create a layout file for each Fragment. 5. Create a new FragmentPagerAdapter class to manage the Fragments. 6. Create a layout file for the Activity which will contain the TableLayout and ViewPager. 7. Add the TableLayout and ViewPager to the layout file. 8. Initialize the ViewPager in the Activity and set the FragmentPagerAdapter. 9. Create a new TabLayout and add it to the layout file. 10. Add the TabLayout to the ViewPager. Example code: 1. Add the dependencies in the build.gradle file: ``` dependencies { implementation 'com.google.android.material:material:1.4.0' implementation 'androidx.viewpager2:viewpager2:1.0.0' } ``` 2. Create a new Fragment class for each tab: ``` public class TabFragment extends Fragment { private int tabPosition; public TabFragment(int tabPosition) { this.tabPosition = tabPosition; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_tab, container, false); TextView textView = view.findViewById(R.id.tab_text); textView.setText(getString(R.string.tab_text, tabPosition + 1)); return view; } } ``` 3. Create a layout file for each Fragment: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tab_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:textAppearanceLarge" /> </LinearLayout> ``` 4. Create a new FragmentPagerAdapter class to manage the Fragments: ``` public class TabAdapter extends FragmentStateAdapter { public TabAdapter(FragmentActivity activity) { super(activity); } @Override public Fragment createFragment(int position) { return new TabFragment(position); } @Override public int getItemCount() { return 3; } } ``` 5. Create a layout file for the Activity which will contain the TableLayout and ViewPager: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"/> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout> ``` 6. Initialize the ViewPager in the Activity and set the FragmentPagerAdapter: ``` public class MainActivity extends AppCompatActivity { private ViewPager2 viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabLayout tabLayout = findViewById(R.id.tab_layout); viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(new TabAdapter(this)); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText("Tab " + (position + 1)) ).attach(); } } ``` 7. Create a new TabLayout and add it to the layout file: ``` <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"/> ``` 8. Add the TabLayout to the ViewPager: ``` TabLayout tabLayout = findViewById(R.id.tab_layout); viewPager.setAdapter(new TabAdapter(this)); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText("Tab " + (position + 1)) ).attach(); ``` This will create a TableLayout with ViewPager and Fragment. The user can swipe left and right to navigate between tabs. Each tab will display a Fragment with a TextView showing the tab number.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值