Android ViewPager2 + TabLayout + BottomNavigationView

来源:https://www.cnblogs.com/askajohnny/archive/2022/12/05/16952119.html
-Advertisement-
Play Games

Android ViewPager2 + TabLayout + BottomNavigationView 實際案例 本篇主要介紹一下 ViewPager2 + TabLayout + BottomNavigationView 的結合操作 概述 相信大家都看過今日頭條的的樣式 如下: 頂部有這種ta ...


Android ViewPager2 + TabLayout + BottomNavigationView 實際案例

本篇主要介紹一下 ViewPager2 + TabLayout + BottomNavigationView 的結合操作

2022-11-25 18.09.09

概述

相信大家都看過今日頭條的的樣式 如下: 頂部有這種tab 並且是可以滑動的, 這就是本篇所介紹的 ViewPager2 + TabLayout 的組合 下麵來看看如何實現把

image-20221125174731255

實現思路

1.Activity 佈局文件中引入BottomNavigationView 和 FragmentContainerView控制項
2.編寫 TabLayoutHomeFragment 佈局文件
3.編寫 Fragment 用於集成ViewPager2 和TabLayout
4. 編寫 RecFragment 用於繼承RecycleView 展示
5.實現 ViewPager2TabLayoutActivity

代碼實現

1.Activity 佈局文件中引入BottomNavigationView 和 FragmentContainerView控制項

其中 menu 使用上一篇中的指定的 menu

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewPager2TabLayoutActivity">
    
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/container_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/bootomnav3"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bootomnav3"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/bottom_item_menu"
        app:labelVisibilityMode="labeled"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

image-20221125175220781

2.編寫 TabLayoutHomeFragment 佈局文件

主要想在這個 Home首頁 Fragment 中 實現TabLayout 和 ViewPager2滑動功能

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".tablayout.TabLayoutHomeFragment">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/mytablayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="auto"
        app:tabGravity="start"
        app:tabBackground="@color/pink"
        app:tabTextColor="@color/white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/myviepage2"
        />
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/myviepage2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toBottomOf="@id/mytablayout2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

3. 編寫 TabLayoutHomeFragment代碼部分 用於集成ViewPager2 和TabLayout

package com.johnny.slzzing.tablayout;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.johnny.slzzing.BottomFragment;
import com.johnny.slzzing.R;
import com.johnny.slzzing.RecFragment;

import java.util.Arrays;
import java.util.List;

public class TabLayoutHomeFragment2 extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String TAG = "TabLayoutHomeFragment";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private ViewPager2 viewPager2;
    private TabLayout tabLayout;

    public TabLayoutHomeFragment2() {}

    public static TabLayoutHomeFragment2 newInstance(String param1, String param2) {
        TabLayoutHomeFragment2 fragment = new TabLayoutHomeFragment2();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_tab_layout_home2, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewPager2 = view.findViewById(R.id.myviepage2);
        viewPager2.setSaveEnabled(false);
        tabLayout = view.findViewById(R.id.mytablayout2);
        List<String> titleList = initPageTitleList();
        TabLayoutChildViewPager tabLayoutChildViewPager =
                new TabLayoutChildViewPager(getActivity(),initChildFragmentList());
         //重點!! ViewPager2綁定Adapter
        viewPager2.setAdapter(tabLayoutChildViewPager);
         //重點!! 關聯 TabLayout 和 ViewPager2
        new TabLayoutMediator(tabLayout, viewPager2, true,
                (tab, position) -> tab.setText(titleList.get(position)))
                .attach();

    }

    private List<String> initPageTitleList() {
       return Arrays.asList("推薦","關註","娛樂","游戲","電影", "電視劇","實時新聞");
    }

    private List<Fragment> initChildFragmentList() {
        //在tablayout 的第一個fragment 中使用 RecycleView 優化一下頁面
        RecFragment recFragment = new RecFragment();
        //BottomFragment bottomFragment = BottomFragment.newInstance("推薦", "");
        BottomFragment bottomFragment2 = BottomFragment.newInstance("關註", "");
        BottomFragment bottomFragment3 = BottomFragment.newInstance("娛樂", "");
        BottomFragment bottomFragment4 = BottomFragment.newInstance("游戲", "");
        BottomFragment bottomFragment5 = BottomFragment.newInstance("電影", "");
        BottomFragment bottomFragment6 = BottomFragment.newInstance("電視劇", "");
        BottomFragment bottomFragment7 = BottomFragment.newInstance("實時新聞", "");

        return Arrays.asList(
                recFragment,
                bottomFragment2,
                bottomFragment3,
                bottomFragment4,
                bottomFragment5,
                bottomFragment6,
                bottomFragment7);
    }

    static class TabLayoutChildViewPager extends FragmentStateAdapter{

        private List<Fragment> fragmentList;



        public TabLayoutChildViewPager(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragmentList) {
            super(fragmentActivity);
            this.fragmentList = fragmentList;
        }



        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getItemCount() {
            return fragmentList.size();
        }
    }
}

4. 編寫 RecFragment 用於繼承RecycleView 展示

主要是優化TabLayout 的第一個fragment 樣式

package com.johnny.slzzing;

import static com.johnny.slzzing.R.drawable.discountberry;
import static com.johnny.slzzing.R.drawable.discountbrocoli;
import static com.johnny.slzzing.R.drawable.discountmeat;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RecFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RecFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private RecyclerView discountRecyclerView;
    private DiscountedProductAdapter discountedProductAdapter;

    public RecFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RecFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RecFragment newInstance(String param1, String param2) {
        RecFragment fragment = new RecFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_rec, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        discountRecyclerView = view.findViewById(R.id.discountedRecycler);
        setDiscountedRecycler(initDiscountList());
    }

    private List<DiscountedProducts> initDiscountList() {
        List<DiscountedProducts> discountedProductsList = new ArrayList<>();
        discountedProductsList.add(new DiscountedProducts(1, discountberry, "草莓", "草莓,多年生草本植物。高10-40釐米,莖低於葉或近相等,密被開展黃色柔毛"));
        discountedProductsList.add(new DiscountedProducts(2, discountbrocoli, "花菜","花椰菜(是十字花科、芸薹屬植物野甘藍的變種。"));
        discountedProductsList.add(new DiscountedProducts(3, discountmeat, "西紅柿", "番茄 是茄科茄屬 [2]  一年生或多年生草本植物,體高0.6-2米,全體生粘質腺毛,有強烈氣味,莖易倒伏,葉羽狀複葉或羽狀深裂"));
        discountedProductsList.add(new DiscountedProducts(4, discountberry, "西瓜","西瓜 一年生蔓生藤本;莖、枝粗壯,具明顯的棱。卷鬚較粗壯,具短柔毛,葉柄粗,密被柔毛"));
        discountedProductsList.add(new DiscountedProducts(5, discountbrocoli,  "南瓜","南瓜 葫蘆科南瓜屬的一個種,一年生蔓生草本植物"));
        discountedProductsList.add(new DiscountedProducts(6, discountmeat, "獼猴桃", "中華獼猴桃 是獼猴桃科、獼猴桃屬大植物。大型落葉藤本;幼一枝或厚或薄地被有灰白色茸毛或褐色長硬毛或鐵鏽色硬毛狀刺毛,老時禿凈或留有斷損殘毛"));
        discountedProductsList.add(new DiscountedProducts(7, discountberry, "草莓", "草莓,多年生草本植物。高10-40釐米,莖低於葉或近相等,密被開展黃色柔毛"));
        discountedProductsList.add(new DiscountedProducts(8, discountbrocoli, "花菜","花椰菜 是十字花科、芸薹屬植物野甘藍的變種。"));
        discountedProductsList.add(new DiscountedProducts(9, discountmeat, "西紅柿", "番茄 是茄科茄屬 [2]  一年生或多年生草本植物,體高0.6-2米,全體生粘質腺毛,有強烈氣味,莖易倒伏,葉羽狀複葉或羽狀深裂"));
        discountedProductsList.add(new DiscountedProducts(10, discountberry, "西瓜","西瓜 一年生蔓生藤本;莖、枝粗壯,具明顯的棱。卷鬚較粗壯,具短柔毛,葉柄粗,密被柔毛"));
        discountedProductsList.add(new DiscountedProducts(11, discountbrocoli,  "南瓜","南瓜 葫蘆科南瓜屬的一個種,一年生蔓生草本植物"));
        discountedProductsList.add(new DiscountedProducts(12, discountmeat, "獼猴桃", "中華獼猴桃 是獼猴桃科、獼猴桃屬大植物。大型落葉藤本;幼一枝或厚或薄地被有灰白色茸毛或褐色長硬毛或鐵鏽色硬毛狀刺毛,老時禿凈或留有斷損殘毛"));
        return discountedProductsList ;
    }

    private void setDiscountedRecycler(List<DiscountedProducts> dataList) {
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        discountedProductAdapter = new DiscountedProductAdapter(getContext(),dataList);
        discountRecyclerView.setLayoutManager(layoutManager);
        discountRecyclerView.setAdapter(discountedProductAdapter);
    }
}

5.實現 ViewPager2TabLayoutActivity

package com.johnny.slzzing;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentContainerView;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;
import com.johnny.slzzing.tablayout.TabLayoutHomeFragment2;

import java.util.HashMap;
import java.util.Map;

public class ViewPager2TabLayoutActivity extends AppCompatActivity {

    BottomNavigationView bottomNavigationView;
    FragmentContainerView fragmentContainerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager2_tab_layout);
        bottomNavigationView = findViewById(R.id.bootomnav3);
        fragmentContainerView  = findViewById(R.id.container_view);
        Map<Integer, Fragment> fragmentMap = new HashMap<>();
        TabLayoutHomeFragment2 tabLayoutHomeFragment2 = new TabLayoutHomeFragment2();
        //這裡 第一個home fragment 使用上面編寫的 TabLayoutHomeFragment2
        fragmentMap.put(R.id.home_item,tabLayoutHomeFragment2);
        fragmentMap.put(R.id.type_item,Bottom2Fragment.newInstance("我是typefragment", ""));
        fragmentMap.put(R.id.add_item,Bottom2Fragment.newInstance("我是addfragment", ""));
        fragmentMap.put(R.id.setting_item,Bottom2Fragment.newInstance("我是settingfragment", ""));
        //bottomNavigationView 點擊用於替換 FragmentContainerView
        bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();
                switch (itemId){
                    case R.id.home_item:
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.container_view, fragmentMap.get(R.id.home_item))
                                .commit();
                        break;
                    case R.id.type_item:
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.container_view, fragmentMap.get(R.id.type_item))
                                .commit();
                    case R.id.add_item:
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.container_view, fragmentMap.get(R.id.add_item))
                                .commit();
                    case R.id.setting_item:
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.container_view, fragmentMap.get(R.id.setting_item))
                                .commit();
                }
                return true;
            }
        });
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container_view, fragmentMap.get(R.id.home_item))
                .commit();


    }
}

效果

可以看到 頂部有類似 今日頭條的 Tab 並且可以滑動喲

image-20221125180539423

總結

本篇主要介紹了 ViewPager2 + TabLayout 的一個集成 實現類似今日頭條的頂部Tab 並且支持滑動

核心聯動代碼

不同於ViewPager , ViewPager2 使用 TabLayoutMediator 來聯動TabLayout 和ViewPager2 以及 tab的標題,註意最後要 attach()

viewPager2.setAdapter(tabLayoutChildViewPager);
new TabLayoutMediator(tabLayout, viewPager2, true,
        (tab, position) -> tab.setText(titleList.get(position)))
        .attach();

歡迎大家訪問 個人博客 Johnny小屋
歡迎關註個人公眾號

歡迎關註個人公眾號


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一.小結 1.每個容器都有一個佈局管理器,它按照所需的位置在容器中定位和放置組件。三個簡單且常用的佈局管理器是FlowLayout、GridLayout和BorderLayout。 2.可以將JPane1作為子容器來將組件分組以得到所需的佈局。 ·使用add方法將組件放到JFrame和JPanel。 ...
  • 安裝 vim 插件管理工具 #vim插件管理-插件 https://github.com/VundleVim/Vundle.vim git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim 編寫 vi ...
  • 非對稱加解密應用廣泛,它的存在是致力於解決密鑰通過公共通道傳輸這一經典難題。對稱加密有一個天然的缺點,就是加密方和解密方都要持有同樣的密鑰,而這個密鑰在傳遞過程中有可能會被截獲,從而使加解密失效。 ...
  • To be, or not to be - that is the question. PowerBuilder編程新思維6:裝飾(用最簡單的方式做框架) 問題 這一章,是寫得最艱難的一章,原因有四: 一、WUI的範疇實在太大了 第二部分Outside原計劃寫兩部分內容Dui和Wui,但是發現如果寫 ...
  • 前言 生活中我們看待一個事物總有不同的態度,比如半瓶水,悲觀的人會覺得只有半瓶水了,而樂觀的人則會認為還有半瓶水呢。很多技術思想往往源於生活,因此在多個線程併發訪問數據的時候,有了悲觀鎖和樂觀鎖。 悲觀鎖認為這個數據肯定會被其他線程給修改了,那我就給它上鎖,只能自己訪問,要等我訪問完,其他人才能訪問 ...
  • 在之前的文章中,棧長介紹了 LongAdder 的使用,性能實在太炸了,你還在用 AtomicInteger、AtomicLong 嗎?如果你還不知道 LongAdder,趕緊看我之前寫的那篇文章。 上次也提到了,在 JDK 8+ 中的 atomic 包下,還有另外一個兄弟類:LongAccumul ...
  • 在 C++11 之前,C++ 編程只能使用 C-style 日期時間庫,其精度只有秒級別,這對於有高精度要求的程式來說,是不夠的。但這個問題在C++11 中得到瞭解決,C++11 中不僅擴展了對於精度的要求,也為不同系統的時間要求提供了支持。另一方面,對於只能使用 C-style 日期時間庫的程式來... ...
  • Java封裝OkHttp3工具類,適用於Java後端開發者。 說實在話,用過挺多網路請求工具,有過java原生的,HttpClient3和4,但是個人感覺用了OkHttp3之後,之前的那些完全不想再用了。 怎麼說呢,代碼輕便,使用起來很很很靈活,響應快,比起HttpClient好用許多。當然,這些是 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...