任务提出

【Android】通过Tencent的IM demo 研究使用View Pager2 进行 Fragment 的片段切换_开发语言


在 run 这个Demo的时候,想看看上面的实现的方式是如何的。

参考ViewPager 2 使用讲解

学以致用

只要通过查阅源代码实现不同的想法,例如
首先先照搬整个的Activity的MainActivity来看看:
比较长,可以直接跳到下面的细节划分。

/**
 * Chris Read it on May 10th 2020
 * 这个对象是整个DEMO的主对象,通过Login之后就会登录到该Activity并进行展示;
 * 主要好奇的点在于是否时候Fragment 片段的方式实现的三个不同的功能模块切换;还得read 一哈代码先!
 */
public class MainActivity extends BaseLightActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private TextView mConversationBtnText;
    private TextView mContactBtnText;
    private TextView mProfileSelfBtnText;
    private View mConversationBtn;
    private View mContactBtn;
    private View mProfileSelfBtn;
    private ImageView mConversationBtnIcon;
    private ImageView mContactBtnIcon;
    private ImageView mProfileSelfBtnIcon;
    private TextView mMsgUnread;
    private TextView mNewFriendUnread;
    private View mLastTab;

    private TitleBarLayout mainTitleBar;
    private Menu menu;

    private ViewPager2 mainViewPager;
    private List<Fragment> fragments;

    private int count = 0;
    private long lastClickTime = 0;

    private static WeakReference<MainActivity> instance;
    // 对Activity 进行Create初始化操作

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        DemoLog.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        instance = new WeakReference<>(this);
        //这几行代码似乎是验证推送的代码,暂时没有太多关注
        DemoApplication.instance().initPush();
        DemoApplication.instance().bindUserID(UserInfo.getInstance().getUserId());
        initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        DemoLog.i(TAG, "onNewIntent");
        setIntent(intent);
        DemoApplication.instance().initPush();
        DemoApplication.instance().bindUserID(UserInfo.getInstance().getUserId());
    }
    //对所有的UI进行初始化处理
    private void initView() {
        setContentView(R.layout.main_activity);

        mainTitleBar = findViewById(R.id.main_title_bar);
        initMenuAction();
        mConversationBtnText = findViewById(R.id.conversation);
        mContactBtnText = findViewById(R.id.contact);
        mProfileSelfBtnText = findViewById(R.id.mine);
        mConversationBtnIcon = findViewById(R.id.tab_conversation_icon);
        mContactBtnIcon = findViewById(R.id.tab_contact_icon);
        mProfileSelfBtnIcon = findViewById(R.id.tab_profile_icon);
        mConversationBtn = findViewById(R.id.conversation_btn_group);
        mContactBtn = findViewById(R.id.contact_btn_group);
        mProfileSelfBtn = findViewById(R.id.myself_btn_group);
        mMsgUnread = findViewById(R.id.msg_total_unread);
        mNewFriendUnread = findViewById(R.id.new_friend_total_unread);
        //fragment 片段切换,保存三种Fragment:消息;通讯录;自己
        fragments = new ArrayList<>();
        fragments.add(new TUIConversationFragment());
        fragments.add(new TUIContactFragment());
        fragments.add(new ProfileFragment());
        //这个是fragment切换的核心代码和对象
        mainViewPager = findViewById(R.id.view_pager);
        //MainActivity最终还是FragmentActivity的子类,这里就可以适配自己写的FragmentAdapter对象
        FragmentAdapter fragmentAdapter = new FragmentAdapter(this);
        fragmentAdapter.setFragmentList(fragments);
        // 关闭左右滑动切换页面
        mainViewPager.setUserInputEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mainViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
                    switch(position){
                        case 0:
                            tabClick(mConversationBtn);
                            break;
                        case 1:
                            tabClick(mContactBtn);
                            break;
                        default:
                            tabClick(mProfileSelfBtn);
                            break;
                    }
                }
            });
        }
        // 设置缓存数量为4 避免销毁重建
        mainViewPager.setOffscreenPageLimit(4);
        mainViewPager.setAdapter(fragmentAdapter);
//        mainViewPager.setCurrentItem(0, true);
        setConversationTitleBar();
        if (mLastTab == null) {
//            mLastTab = mConversationBtn;
//            mLastTab = mContactBtn;
        } else {
            // 初始化时,强制切换tab到上一次的位置
            View tmp = mLastTab;
            mLastTab = null;
            tabClick(tmp);//三个方法共用,所以导致必须有一个mLastTab,避免重复获取数据
            mLastTab = tmp;
        }

        prepareToClearAllUnreadMessage();
    }
    //这个是Menu的代码实现的,主要就是通过监听点击;先研究一哈这个menu是怎么实现的吧
    private void initMenuAction() {
        int titleBarIconSize = getResources().getDimensionPixelSize(R.dimen.demo_title_bar_icon_size);
        mainTitleBar.getLeftIcon().setMaxHeight(titleBarIconSize);
        mainTitleBar.getLeftIcon().setMaxWidth(titleBarIconSize);
        mainTitleBar.getRightIcon().setMaxHeight(titleBarIconSize);
        mainTitleBar.getRightIcon().setMaxWidth(titleBarIconSize);
        mainTitleBar.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (menu == null) {
                    return;
                }
                if (menu.isShowing()) {
                    menu.hide();
                } else {
                    menu.show();
                }
            }
        });
    }
    // 顾名思义,这个是对所有未读消息进行删除的前提准备
    private void prepareToClearAllUnreadMessage() {
        mMsgUnread.setOnTouchListener(new View.OnTouchListener() {
            private float downX;
            private float downY;
            private boolean isTriggered = false;
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        downX = mMsgUnread.getX();
                        downY = mMsgUnread.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (isTriggered) {
                            return true;
                        }
                        float viewX = view.getX();
                        float viewY = view.getY();
                        float eventX = event.getX();
                        float eventY = event.getY();
                        float translationX = eventX + viewX - downX;
                        float translationY = eventY + viewY - downY;
                        view.setTranslationX(translationX);
                        view.setTranslationY(translationY);
                        // 移动的 x 和 y 轴坐标超过一定像素则触发一键清空所有会话未读
                        if (Math.abs(translationX) > 200|| Math.abs(translationY) > 200) {
                            isTriggered = true;
                            mMsgUnread.setVisibility(View.GONE);
                            triggerClearAllUnreadMessage();
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        view.setTranslationX(0);
                        view.setTranslationY(0);
                        isTriggered = false;
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        isTriggered = false;
                        break;
                }

                return true;
            }
        });
    }
    //该方法会被在prepareToClearAllUnreadMessage中进行调用
    private void triggerClearAllUnreadMessage() {
        V2TIMManager.getMessageManager().markAllMessageAsRead(new V2TIMCallback() {
            @Override
            public void onSuccess() {
                Log.i(TAG, "markAllMessageAsRead success");
                ToastUtil.toastShortMessage(MainActivity.this.getString(R.string.mark_all_message_as_read_succ));
            }

            @Override
            public void onError(int code, String desc) {
                Log.i(TAG, "markAllMessageAsRead error:" + code + ", desc:" + ErrorMessageConverter.convertIMError(code, desc));
                ToastUtil.toastShortMessage(MainActivity.this.getString(R.string.mark_all_message_as_read_err_format, code, ErrorMessageConverter.convertIMError(code, desc)));
                mMsgUnread.setVisibility(View.VISIBLE);
            }
        });
    }

    public void tabClick(View view) {

        DemoLog.i(TAG, "tabClick last: " + mLastTab + " current: " + view);
        if (mLastTab != null && mLastTab.getId() == view.getId()) {
            return;
        }
        mLastTab = view;
        resetMenuState();
        switch (view.getId()) {
            case R.id.conversation_btn_group:
                mainViewPager.setCurrentItem(0, false);
                setConversationTitleBar();
                mConversationBtnText.setTextColor(getResources().getColor(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_selected_text_color)));
                mConversationBtnIcon.setBackground(getResources().getDrawable(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_conversation_selected_bg)));
                break;
            case R.id.contact_btn_group:
                mainViewPager.setCurrentItem(1, false);
                setContactTitleBar();
                mContactBtnText.setTextColor(getResources().getColor(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_selected_text_color)));
                mContactBtnIcon.setBackground(getResources().getDrawable(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_contact_selected_bg)));
                break;
            case R.id.myself_btn_group:
                mainViewPager.setCurrentItem(2, false);
                setProfileTitleBar();
                mProfileSelfBtnText.setTextColor(getResources().getColor(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_selected_text_color)));
                mProfileSelfBtnIcon.setBackground(getResources().getDrawable(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_profile_selected_bg)));
                break;
            default:
                break;
        }
    }
    //之前就对这个通过的TitleBarLayout进行设计和UI的适配了~这就省了很多时间,这个组件可以用来直接copy使用!perfect!
    private void setConversationTitleBar() {
        mainTitleBar.setTitle(getResources().getString(R.string.conversation_title), ITitleBarLayout.Position.MIDDLE);
        mainTitleBar.getLeftGroup().setVisibility(View.GONE);
        mainTitleBar.getRightGroup().setVisibility(View.VISIBLE);
        mainTitleBar.setRightIcon(TUIThemeManager.getAttrResId(this, R.attr.demo_title_bar_more));
        setConversationMenu();
    }

    private void setConversationMenu() {
        menu = new Menu(this, mainTitleBar.getRightIcon());
        PopActionClickListener popActionClickListener = new PopActionClickListener() {
            @Override
            public void onActionClick(int position, Object data) {
                PopMenuAction action = (PopMenuAction) data;
                if (TextUtils.equals(action.getActionName(), getResources().getString(R.string.start_conversation))) {
                    TUIUtils.startActivity("StartC2CChatActivity", null);
                }

                if (TextUtils.equals(action.getActionName(), getResources().getString(R.string.create_private_group))) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(TUIConversationConstants.GroupType.TYPE, TUIConversationConstants.GroupType.PRIVATE);
                    TUIUtils.startActivity("StartGroupChatActivity", bundle);
                }
                if (TextUtils.equals(action.getActionName(), getResources().getString(R.string.create_group_chat))) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(TUIConversationConstants.GroupType.TYPE, TUIConversationConstants.GroupType.PUBLIC);
                    TUIUtils.startActivity("StartGroupChatActivity", bundle);
                }
                if (TextUtils.equals(action.getActionName(), getResources().getString(R.string.create_chat_room))) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(TUIConversationConstants.GroupType.TYPE, TUIConversationConstants.GroupType.CHAT_ROOM);
                    TUIUtils.startActivity("StartGroupChatActivity", bundle);
                }
                if (TextUtils.equals(action.getActionName(), getResources().getString(R.string.create_community))) {
                    Bundle bundle = new Bundle();
                    bundle.putInt(TUIConversationConstants.GroupType.TYPE, TUIConversationConstants.GroupType.COMMUNITY);
                    TUIUtils.startActivity("StartGroupChatActivity", bundle);
                }
                menu.hide();
            }
        };

        // 设置右上角+号显示PopAction
        List<PopMenuAction> menuActions = new ArrayList<>();

        PopMenuAction action = new PopMenuAction();

        action.setActionName(getResources().getString(R.string.start_conversation));
        action.setActionClickListener(popActionClickListener);
        action.setIconResId(R.drawable.create_c2c);
        menuActions.add(action);
        action = new PopMenuAction();
        action.setActionName(getResources().getString(R.string.create_private_group));
        action.setIconResId(R.drawable.group_icon);
        action.setActionClickListener(popActionClickListener);
        menuActions.add(action);

        action = new PopMenuAction();
        action.setActionName(getResources().getString(R.string.create_group_chat));
        action.setIconResId(R.drawable.group_icon);
        action.setActionClickListener(popActionClickListener);
        menuActions.add(action);

        action = new PopMenuAction();
        action.setActionName(getResources().getString(R.string.create_chat_room));
        action.setIconResId(R.drawable.group_icon);
        action.setActionClickListener(popActionClickListener);
        menuActions.add(action);

        action = new PopMenuAction();
        action.setActionName(getResources().getString(R.string.create_community));
        action.setIconResId(R.drawable.group_icon);
        action.setActionClickListener(popActionClickListener);
        menuActions.add(action);

        menu.setMenuAction(menuActions);
    }

    private void setContactTitleBar() {
        mainTitleBar.setTitle(getResources().getString(R.string.contact_title), ITitleBarLayout.Position.MIDDLE);
        mainTitleBar.getLeftGroup().setVisibility(View.GONE);
        mainTitleBar.getRightGroup().setVisibility(View.VISIBLE);
        mainTitleBar.setRightIcon(TUIThemeManager.getAttrResId(this, R.attr.demo_title_bar_more));
        setContactMenu();
    }
    //这个是针对通讯录的menu进行设计跳转到不同的Activity之中
    public void setContactMenu() {
        menu = new Menu(this, mainTitleBar.getRightIcon());
        List<PopMenuAction> menuActionList = new ArrayList<>(2);
        PopActionClickListener popActionClickListener = new PopActionClickListener() {
            @Override
            public void onActionClick(int index, Object data) {
                PopMenuAction action = (PopMenuAction) data;
                if (TextUtils.equals(action.getActionName(), getResources().getString(R.string.add_friend))) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(TUIContactConstants.GroupType.GROUP, false);
                    TUIUtils.startActivity("AddMoreActivity", bundle);
                }
                if (TextUtils.equals(action.getActionName(), getResources().getString(R.string.add_group))) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(TUIContactConstants.GroupType.GROUP, true);
                    TUIUtils.startActivity("AddMoreActivity", bundle);
                }
                menu.hide();
            }
        };
        PopMenuAction action = new PopMenuAction();
        action.setActionName(getResources().getString(R.string.add_friend));
        action.setIconResId(R.drawable.demo_add_friend);
        action.setActionClickListener(popActionClickListener);
        menuActionList.add(action);

        action = new PopMenuAction();
        action.setActionName(getResources().getString(R.string.add_group));
        action.setIconResId(R.drawable.demo_add_group);
        action.setActionClickListener(popActionClickListener);
        menuActionList.add(action);
        menu.setMenuAction(menuActionList);
    }
    //这个方法对ME这个模块的Title进行适配操作
    private void setProfileTitleBar() {
        mainTitleBar.getLeftGroup().setVisibility(View.GONE);
        mainTitleBar.getRightGroup().setVisibility(View.GONE);
        mainTitleBar.setTitle(getResources().getString(R.string.profile), ITitleBarLayout.Position.MIDDLE);
    }
    //对Tab的消息、通讯录、我 这些模块进行重设
    private void resetMenuState() {
        mConversationBtnText.setTextColor(getResources().getColor(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_normal_text_color)));
        mConversationBtnIcon.setBackground(getResources().getDrawable(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_conversation_normal_bg)));
        mContactBtnText.setTextColor(getResources().getColor(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_normal_text_color)));
        mContactBtnIcon.setBackground(getResources().getDrawable(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_contact_normal_bg)));
        mProfileSelfBtnText.setTextColor(getResources().getColor(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_normal_text_color)));
        mProfileSelfBtnIcon.setBackground(getResources().getDrawable(TUIThemeManager.getAttrResId(this, R.attr.demo_main_tab_profile_normal_bg)));
    }
    //对未读短信进行监听操作,对未读信息做UI处理(文本加工)
    private final V2TIMConversationListener unreadListener = new V2TIMConversationListener() {
        @Override
        public void onTotalUnreadMessageCountChanged(long totalUnreadCount) {
            if (totalUnreadCount > 0) {
                mMsgUnread.setVisibility(View.VISIBLE);
            } else {
                mMsgUnread.setVisibility(View.GONE);
            }
            String unreadStr = "" + totalUnreadCount;
            if (totalUnreadCount > 100) {
                unreadStr = "99+";
            }
            mMsgUnread.setText(unreadStr);
            // 华为离线推送角标 三方调用,暂未知其主要功能
            OfflineMessageDispatcher.updateBadge(MainActivity.this, (int) totalUnreadCount);
        }
    };
    //该监听式实现对用户添加删除的监听的,refreshFriendApplicationUnreadCount更新用户通讯录列表
    private final V2TIMFriendshipListener friendshipListener = new V2TIMFriendshipListener() {
        @Override
        public void onFriendApplicationListAdded(List<V2TIMFriendApplication> applicationList) {
            refreshFriendApplicationUnreadCount();
        }

        @Override
        public void onFriendApplicationListDeleted(List<String> userIDList) {
            refreshFriendApplicationUnreadCount();
        }

        @Override
        public void onFriendApplicationListRead() {
            refreshFriendApplicationUnreadCount();
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    protected void onStart() {
        DemoLog.i(TAG, "onStart");
        super.onStart();
    }

    @Override
    protected void onResume() {
        DemoLog.i(TAG, "onResume");
        super.onResume();
        registerUnreadListener();
        handleOfflinePush();
    }
    //调用SDK所提供的进行未读信息监听
    private void registerUnreadListener() {
        V2TIMManager.getConversationManager().addConversationListener(unreadListener);
        V2TIMManager.getConversationManager().getTotalUnreadMessageCount(new V2TIMValueCallback<Long>() {
            @Override
            public void onSuccess(Long aLong) {
                runOnUiThread(() -> unreadListener.onTotalUnreadMessageCountChanged(aLong));
            }

            @Override
            public void onError(int code, String desc) {

            }
        });

        V2TIMManager.getFriendshipManager().addFriendListener(friendshipListener);
        refreshFriendApplicationUnreadCount();
    }
    //对用户通讯录的方法操作就基本在这里进行展示了,主要的核心在于回调的监听
    private void refreshFriendApplicationUnreadCount() {
        V2TIMManager.getFriendshipManager().getFriendApplicationList(new V2TIMValueCallback<V2TIMFriendApplicationResult>() {
            @Override
            public void onSuccess(V2TIMFriendApplicationResult v2TIMFriendApplicationResult) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //只是用户的通讯录即用户的朋友进行书数目变化而已和前面的短信信息异曲同工
                        int unreadCount = v2TIMFriendApplicationResult.getUnreadCount();
                        if (unreadCount > 0) {
                            mNewFriendUnread.setVisibility(View.VISIBLE);
                        } else {
                            mNewFriendUnread.setVisibility(View.GONE);
                        }
                        String unreadStr = "" + unreadCount;
                        if (unreadCount > 100) {
                            unreadStr = "99+";
                        }
                        mNewFriendUnread.setText(unreadStr);
                    }
                });
            }

            @Override
            public void onError(int code, String desc) {

            }
        });
    }
    //离线推送,暂时不用管这个吧!这个技术好像公司的IM才刚
    private void handleOfflinePush() {
        if (V2TIMManager.getInstance().getLoginStatus() == V2TIMManager.V2TIM_STATUS_LOGOUT) {
            Intent intent = new Intent(MainActivity.this, SplashActivity.class);
            if (getIntent() != null) {
                intent.setData(getIntent().getData());
                intent.putExtras(getIntent());
            }
            startActivity(intent);
            finish();
            return;
        }

        final OfflineMessageBean bean = OfflineMessageDispatcher.parseOfflineMessage(getIntent());
        if (bean != null) {
            setIntent(null);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (manager != null) {
                manager.cancelAll();
            }

            if (bean.action == OfflineMessageBean.REDIRECT_ACTION_CHAT) {
                if (TextUtils.isEmpty(bean.sender)) {
                    return;
                }
                TUIUtils.startChat(bean.sender, bean.nickname, bean.chatType);
            }
        }
    }

    @Override
    protected void onPause() {
        DemoLog.i(TAG, "onPause");
        super.onPause();
        V2TIMManager.getConversationManager().removeConversationListener(unreadListener);
        V2TIMManager.getFriendshipManager().removeFriendListener(friendshipListener);
    }

    @Override
    protected void onStop() {
        DemoLog.i(TAG, "onStop");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        DemoLog.i(TAG, "onDestroy");
        mLastTab = null;
        super.onDestroy();
    }

    public static void finishMainActivity() {
        if (instance != null && instance.get() != null) {
            instance.get().finish();
        }
    }

}

细节划分

  • 首先肯定需要fragment片段作为每一个切换的片段。
    在Activity的生命周期中对fragment进行创建并加入到实际的数据结构中进行匹配。
private ViewPager2 mainViewPager;
    private List<Fragment> fragments;
  • 由于每个Fragment的实现比较繁琐,主要知道每个fragment有自己的任务实现即可,当透明的。
//fragment 片段切换,保存三种Fragment:消息;通讯录;自己
        fragments = new ArrayList<>();
        fragments.add(new TUIConversationFragment());
        fragments.add(new TUIContactFragment());
        fragments.add(new ProfileFragment());
  • 数据都准备好后,需要一个专门的Adapter进行适配,就用到如下所示的自定义Adapter
package com.tencent.qcloud.tim.demo.main;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;


import java.util.List;

public class FragmentAdapter extends FragmentStateAdapter {
    private static final String TAG = FragmentAdapter.class.getSimpleName();

    private List<Fragment> fragmentList;

    public FragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    public FragmentAdapter(@NonNull Fragment fragment) {
        super(fragment);
    }

    public FragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
        super(fragmentManager, lifecycle);
    }

    public void setFragmentList(List<Fragment> fragmentList) {
        this.fragmentList = fragmentList;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        if (fragmentList == null || fragmentList.size() <= position) {
            return new Fragment();
        }
        return fragmentList.get(position);
    }

    @Override
    public int getItemCount() {
        return fragmentList == null ? 0 : fragmentList.size();
    }
}
  • 创建适配器并添加数据
//MainActivity最终还是FragmentActivity的子类,这里就可以适配自己写的FragmentAdapter对象
        FragmentAdapter fragmentAdapter = new FragmentAdapter(this);
        fragmentAdapter.setFragmentList(fragments);

ViewPage2 重头戏

  • 对上述构建的基础进行加载和调整,以适应我们的需求。
//这个是fragment切换的核心代码和对象
        mainViewPager = findViewById(R.id.view_pager);
        // 关闭左右滑动切换页面
        mainViewPager.setUserInputEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mainViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
                    switch(position){
                        case 0:
                            tabClick(mConversationBtn);
                            break;
                        case 1:
                            tabClick(mContactBtn);
                            break;
                        default:
                            tabClick(mProfileSelfBtn);
                            break;
                    }
                }
            });
        }
        // 设置缓存数量为4 避免销毁重建
        mainViewPager.setOffscreenPageLimit(4);
        mainViewPager.setAdapter(fragmentAdapter);

mainViewPager.setAdapter(fragmentAdapter);最关键的不要忘记哟!要不数据给加载上去。

我是将原有的ViewPager2重新进行监听设计,原有的只是点击下面的tag框直接跳转没有一个动画的切换效果。

就如下图所示:

【Android】通过Tencent的IM demo 研究使用View Pager2 进行 Fragment 的片段切换_ico_02

添加滑动的效果

旧代码:

// 关闭左右滑动切换页面
        mainViewPager.setUserInputEnabled(false);

新代码:

mainViewPager.setUserInputEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mainViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
                @Override
                public void onPageSelected(int position) {
                    super.onPageSelected(position);
                    switch(position){
                        case 0:
                            tabClick(mConversationBtn);
                            break;
                        case 1:
                            tabClick(mContactBtn);
                            break;
                        default:
                            tabClick(mProfileSelfBtn);
                            break;
                    }
                }
            });
        }