TabLayout + ViewPager 实现横着的 TabLayout

时间:2021-07-08 05:25:46

先来张效果图:
TabLayout + ViewPager 实现横着的 TabLayout
1.在build.gradle 添加依赖如下:

compile 'com.android.support:design:26.1.0'

2.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">

    <android.support.design.widget.TabLayout  android:id="@+id/tablayout" android:layout_width="match_parent" android:layout_height="60dp" app:tabTextAppearance="@style/TabLayoutText" app:tabSelectedTextColor="@color/text_sel" app:tabTextColor="#000000" app:tabIndicatorColor="@color/text_sel" app:tabIndicatorHeight="1dp"/>

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

</LinearLayout>

3.MainActivity.java

package com.gyq.htablayout;

import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;

import com.gyq.htablayout.adapter.MyPagerAdapter;

public class MainActivity extends AppCompatActivity {
    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    private MyPagerAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAdapter = new MyPagerAdapter(getSupportFragmentManager());
        mTabLayout = (TabLayout)findViewById(R.id.tablayout);
        mViewPager = (ViewPager)findViewById(R.id.viewpager);

        mViewPager.setAdapter(mAdapter);

        mTabLayout.setupWithViewPager(mViewPager);


    }
}

4.BaseFragment.java

package com.gyq.htablayout.base;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public abstract class BaseFragment extends Fragment implements MyToolBarClickListener {
    protected static final int DEFAULT_LOADING_TIME = 2000;
    protected static final int WHAT_LOAD = 1;
    protected static final int WHAT_LOAD_FINISH = 2;
    protected static final int WHAT_REFRESH = 3;

    protected Activity mActivity;
    protected Context mContext;
    protected View mRootView;

    protected ActivityFragmentInject annotation;
    protected int contentViewId;

    protected Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            toHandleMessage(msg);
        }
    };


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();
        mContext = getContext();
        if (!getClass().isAnnotationPresent(ActivityFragmentInject.class)) {
            throw new RuntimeException("must use ActivityFragmentInitParams.class");
        }
        annotation = getClass().getAnnotation(ActivityFragmentInject.class);
        contentViewId = annotation.contentViewId();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = View.inflate(mContext, contentViewId, null);
        }
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        initViewNData();
        return mRootView;
    }

    protected void initViewNData() {
        if (annotation.hasToolbar()) {
            //initToolbar();
        }
        findViewAfterViewCreate();
        initDataAfterFindView();
    }

    protected void initToolbar() {

    }

    protected abstract void toHandleMessage(Message msg);

    protected abstract void findViewAfterViewCreate();

    protected abstract void initDataAfterFindView();


    @Override
    public void leftTextClick(View view) {
    }

    @Override
    public void leftIconClick(View view) {
    }

    @Override
    public void rightTextClick(View view) {
    }

    @Override
    public void rightIconClick(View view) {
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }
}

5.注解

package com.gyq.htablayout.base;

import com.gyq.htablayout.R;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ActivityFragmentInject {
    /** * 顶部局的id * * @return */
    int contentViewId() default R.layout.activity_main;

    /** * 是否存在NavigationView * * @return */
    boolean hasNavigationView() default false;

    /** * 是否存在Toolbar * * @return */
    boolean hasToolbar() default false;

    /** * toolbar的标题id * * @return */
    int toolbarTitle() default -1;

    /** * 左边文本资源id * @return */
    int toolbarLeftText() default -1;

    /** * 右边文本资源id * @return */
    int toolbarRightText() default -1;

    /** * 左边图片资源id * @return */
    int toolbarLeftIcon() default -1;

    /** * 右边图片资源id * @return */
    int toolbarRightIcon() default -1;
}

6.FragmentFactory.java

package com.gyq.htablayout.base;

import com.gyq.htablayout.fragment.NotOpenFragment;
import com.gyq.htablayout.fragment.OpenFragment;

import java.util.HashMap;

public class FragmentFactory {
    private static HashMap<Integer, BaseFragment> mBaseFragments = new HashMap<Integer, BaseFragment>();
    public static BaseFragment createFragment(int position){
        BaseFragment baseFragment = mBaseFragments.get(position);

        if (baseFragment == null) {
            switch (position) {
                case 0:
                    baseFragment = new NotOpenFragment();
                    break;
                case 1:
                    baseFragment = new OpenFragment();
                    break;

            }

        }

        mBaseFragments.put(position, baseFragment);
        return baseFragment;
    }
}

7.MyToolBarClickListener.java

package com.gyq.htablayout.base;

import android.view.View;

public interface MyToolBarClickListener {
    void leftTextClick(View view);
    void leftIconClick(View view);
    void rightTextClick(View view);
    void rightIconClick(View view);
}

8.适配器

package com.gyq.htablayout.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.gyq.htablayout.base.BaseFragment;
import com.gyq.htablayout.base.FragmentFactory;

public class MyPagerAdapter extends FragmentPagerAdapter {
    private String[] mTitles = {"未开通","已开通"};
    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        BaseFragment fragment = FragmentFactory.createFragment(position);
        return fragment;
    }

    @Override
    public int getCount() {
        return mTitles.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles[position];
    }
}

9.NotOpenFragment.java示例代码

package com.gyq.htablayout.fragment;


import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gyq.htablayout.R;
import com.gyq.htablayout.base.ActivityFragmentInject;
import com.gyq.htablayout.base.BaseFragment;

/** * A simple {@link Fragment} subclass. */
@ActivityFragmentInject(
        contentViewId = R.layout.fragment_not_open,
        hasNavigationView = false)
public class NotOpenFragment extends BaseFragment {


    @Override
    protected void toHandleMessage(Message msg) {

    }

    @Override
    protected void findViewAfterViewCreate() {

    }

    @Override
    protected void initDataAfterFindView() {

    }
}

11.其他

//放在colors文件下
<color name="text_sel">#4876FF</color>

//放在styles文件下
<style name="TabLayoutText"> <item name="android:textSize">18sp</item> </style>