• Android学习笔记 27. Fragment + ViewPager


    Android学习笔记

    Android基础开发——Fragment

    27. Fragment + ViewPager

    27.1 fragment与viewPager的联合应用

    ViewPager + Fragment形成翻页效果

    → 减少用户的操作。

    27.2 ViewPager2基本应用

    新的空白工程

    在这里插入图片描述

    布局文件

    
    <LinearLayout 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=".MainActivity">
    
        <androidx.viewpager2.widget.ViewPager2
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/viewpager"
            android:background="#ff00ff"
            />
    
    LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    定义适配器Adapter类

    package com.dingjiaxiong.myviewpagerandfragment;
    
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.RelativeLayout;
    import android.widget.TextView;
    
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class ViewPageAdapter extends RecyclerView.Adapter<ViewPageAdapter.ViewPagerViewHolder> {
    
        private List<String> titles = new ArrayList<>();
    
        public ViewPageAdapter(){
            titles.add("hello");
            titles.add("w");
            titles.add("o");
            titles.add("r");
            titles.add("l");
            titles.add("d");
            titles.add("Android");
            titles.add("Java");
            titles.add("How");
            titles.add("?");
    
        }
    
        @NonNull
        @Override
        public ViewPagerViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewPagerViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_pager,parent,false));
        }
    
    
        //定义view适配
        @Override
        public void onBindViewHolder(@NonNull ViewPagerViewHolder holder, int position) {
            holder.mTv.setText(titles.get(position));
        }
    
        @Override
        public int getItemCount() {
            return 10;
        }
    
        class ViewPagerViewHolder extends RecyclerView.ViewHolder{
    
            TextView mTv;
            RelativeLayout mContainer;
    
            public ViewPagerViewHolder(@NonNull View itemView) {
                super(itemView);
                mContainer = itemView.findViewById(R.id.container);
                mTv = itemView.findViewById(R.id.tvTitle);
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63

    适配布局

    item_pager.xml

    
    
    
        
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    MainActivity.java

    package com.dingjiaxiong.myviewpagerandfragment;
    
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.recyclerview.widget.RecyclerView;
    import androidx.viewpager2.widget.ViewPager2;
    
    import android.os.Bundle;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            ViewPager2 viewPager = findViewById(R.id.viewpager);
    
            ViewPageAdapter viewPageAdapter = new ViewPageAdapter();
    
            viewPager.setAdapter(viewPageAdapter);
    
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    运行

    在这里插入图片描述

    27.3 页面的切换

    更改背景颜色即可

    在这里插入图片描述

    private List colors = new ArrayList<>();
    
    public ViewPageAdapter(){
    
        colors.add(R.color.white);
        colors.add(R.color.black);
        colors.add(R.color.purple_200);
        colors.add(R.color.red);
        colors.add(R.color.purple_500);
        colors.add(R.color.purple_700);
        colors.add(R.color.teal_200);
        colors.add(R.color.teal_700);
        colors.add(R.color.red);
        colors.add(R.color.teal_200);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    运行

    在这里插入图片描述

    27.4 ViewPager的使用流程
    1. 定义ViewPager
    2. 为ViewPager构建Adapter
    27.5 ViewPager + Fragment形成翻页效果

    仿微信

    创建空项目

    MainActivity.java

    package com.dingjiaxiong.wechatpage;
    
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.fragment.app.Fragment;
    import androidx.viewpager2.widget.ViewPager2;
    
    import android.os.Bundle;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    
        ViewPager2 viewPager;
        private LinearLayout llchat , llcontacts , llfind , llprofiles;
        private ImageView ivChat , ivContact , ivFind ,ivMe , ivCurrent;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            initPager();
            initTabView();
    
        }
    
        private void initTabView() {
            llchat = findViewById(R.id.id_tab_weixin);
            llchat.setOnClickListener(this);
            llcontacts = findViewById(R.id.id_tab_cantact);
            llcontacts.setOnClickListener(this);
            llfind = findViewById(R.id.id_tab_search);
            llfind.setOnClickListener(this);
            llprofiles = findViewById(R.id.id_tab_me);
            llprofiles.setOnClickListener(this);
    
            ivChat = findViewById(R.id.tab_iv_weixin);
            ivContact = findViewById(R.id.tab_iv_contact);
            ivFind = findViewById(R.id.tab_iv_search);
            ivMe = findViewById(R.id.tab_iv_me);
    
            ivChat.setSelected(true);
            ivCurrent = ivChat;
    
        }
    
        private void initPager() {
    
            viewPager = findViewById(R.id.id_viewpager);
    
            ArrayList<Fragment> fragments = new ArrayList<>();
            fragments.add(BlankFragment.newInstance("微信聊天"));
            fragments.add(BlankFragment.newInstance("通讯录"));
            fragments.add(BlankFragment.newInstance("发现"));
            fragments.add(BlankFragment.newInstance("我"));
    
            MyFragmentPagerAdapter pagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),getLifecycle(),fragments);
            viewPager.setAdapter(pagerAdapter);
    
            viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                }
    
    
    
                //这里设置,页面改变
                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
                    changeTab(position);
                }
    
                @Override
                public void onPageScrollStateChanged(int state) {
                    super.onPageScrollStateChanged(state);
                }
            });
    
        }
    
        private void changeTab(int position) {
            ivCurrent.setSelected(false);
            switch (position){
                case R.id.id_tab_weixin:
                    viewPager.setCurrentItem(0);
                case 0:
                    ivChat.setSelected(true);
                    ivCurrent = ivChat;
                    break;
                case R.id.id_tab_cantact:
                    viewPager.setCurrentItem(1);
                case 1:
                    ivContact.setSelected(true);
                    ivCurrent = ivContact;
                    break;
                case R.id.id_tab_search:
                    viewPager.setCurrentItem(2);
                case 2:
                    ivFind.setSelected(true);
                    ivCurrent = ivFind;
                    break;
                case R.id.id_tab_me:
                    viewPager.setCurrentItem(3);
                case 3:
                    ivMe.setSelected(true);
                    ivCurrent = ivMe;
                    break;
            }
        }
    
        @Override
        public void onClick(View view) {
            changeTab(view.getId());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120

    BlankFragment.java

    package com.dingjiaxiong.wechatpage;
    
    import android.os.Bundle;
    
    import androidx.fragment.app.Fragment;
    
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    
    /**
     * A simple {@link Fragment} subclass.
     * Use the {@link BlankFragment#newInstance} factory method to
     * create an instance of this fragment.
     */
    public class BlankFragment extends Fragment {
    
        private static final String ARG_TEXT = "param1";
    
    
        // TODO: Rename and change types of parameters
        private String mTextString;
        View rootview;
    
        public BlankFragment() {
            // Required empty public constructor
        }
    
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @return A new instance of fragment BlankFragment.
         */
        // TODO: Rename and change types and number of parameters
        public static BlankFragment newInstance(String param1) {
            BlankFragment fragment = new BlankFragment();
            Bundle args = new Bundle();
            args.putString(ARG_TEXT, param1);
    
            fragment.setArguments(args);
            return fragment;
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getArguments() != null) {
                mTextString = getArguments().getString(ARG_TEXT);
    
            }
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
    
            if(rootview == null){
                rootview =  inflater.inflate(R.layout.fragment_blank, container, false);
            }
            initView();
            return rootview;
        }
    
        private void initView() {
            TextView textView = rootview.findViewById(R.id.text);
            textView.setText(mTextString);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    MyFragmentPagerAdapter.java

    package com.dingjiaxiong.wechatpage;
    
    import androidx.annotation.NonNull;
    import androidx.fragment.app.Fragment;
    import androidx.fragment.app.FragmentManager;
    import androidx.lifecycle.Lifecycle;
    import androidx.viewpager2.adapter.FragmentStateAdapter;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MyFragmentPagerAdapter extends FragmentStateAdapter {
    
        List<Fragment> fragmentList = new ArrayList<>();
    
        public MyFragmentPagerAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle,List<Fragment> fragments) {
            super(fragmentManager, lifecycle);
            fragmentList = fragments;
    
        }
    
        @NonNull
        @Override
        public Fragment createFragment(int position) {
            return fragmentList.get(position);
        }
    
        @Override
        public int getItemCount() {
            return fragmentList.size();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    activity_main.xml

    
    <LinearLayout 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"
        android:orientation="vertical"
        tools:context=".MainActivity">
    
        <androidx.viewpager2.widget.ViewPager2
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/id_viewpager"
            />
    
    
        <include layout="@layout/bottom_layout">include>
    
    LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    bottom_layout.xml

    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:orientation="horizontal"
        android:background="@color/gray"
        >
    
        <LinearLayout
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:id="@+id/id_tab_weixin"
            >
    
            <ImageView
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:id="@+id/tab_iv_weixin"
                android:background="@drawable/tab_weixin"
                />
    
    
            <TextView
                android:layout_width="32dp"
                android:layout_height="wrap_content"
                android:id="@+id/text_weixin"
                android:gravity="center"
                android:text="微信"
                />
    
        LinearLayout>
    
        <LinearLayout
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:id="@+id/id_tab_cantact"
            >
    
            <ImageView
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:id="@+id/tab_iv_contact"
                android:background="@drawable/tab_cantact"
                />
    
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/text_cantact"
                android:gravity="center"
                android:text="通讯录"
                />
    
        LinearLayout>
    
        <LinearLayout
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:id="@+id/id_tab_search"
            >
    
            <ImageView
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:id="@+id/tab_iv_search"
                android:background="@drawable/tab_search"
                />
    
    
            <TextView
                android:layout_width="32dp"
                android:layout_height="wrap_content"
                android:id="@+id/text_search"
                android:gravity="center"
                android:text="发现"
                />
    
        LinearLayout>
    
        <LinearLayout
            android:gravity="center"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_gravity="center"
            android:orientation="vertical"
            android:id="@+id/id_tab_me"
            >
    
            <ImageView
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:id="@+id/tab_iv_me"
                android:background="@drawable/tab_mine"
                />
    
    
            <TextView
                android:layout_width="32dp"
                android:layout_height="wrap_content"
                android:id="@+id/text_me"
                android:gravity="center"
                android:text=""
                />
    
        LinearLayout>
    
    
    
    
    
    LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125

    fragment_blank.xml

    
    <FrameLayout 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"
        tools:context=".BlankFragment">
    
        
        <TextView
            android:id="@+id/text"
            android:gravity="center"
            android:textSize="36sp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="@string/hello_blank_fragment" />
    
    FrameLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    运行效果

    在这里插入图片描述

  • 相关阅读:
    HIPPO-4J 1.3.0 正式发布:支持 Dubbo、RibbitMQ、RocketMQ 框架线程池
    C#算法(12)—对图像像素做X/Y方向的偏移
    async的初始理解以及例子
    Python数据分析案例04——超高维数据的降维(随机森林)、特征工程
    springboot的web开发
    三维地图开发平台-支持离线地图开发
    Java实用类-String
    交换机和路由器技术-36-端口镜像
    【Log4cpp】项目日志Log4cpp的简单使用
    Redis 主从复制
  • 原文地址:https://blog.csdn.net/weixin_44226181/article/details/126259196