拦截tablayout 点击事件,不触发viewpaper滚动 例如登陆检测等场景

Java基础

浏览数:78

2019-10-16

AD:资源代下载服务

场景描述
app架构是底下有四个tab,点击tab切换fragment,但是产品要求,点击tab之前需要检测是否登陆,如果未登录,直接跳转登陆提示,页面不进行切换

首先是架构,我们使用TabLayout + Viewpaper + Fragment 来实现,登录提示,只要拿到TabLayout的Tab 监听它的OnClickListener,可是。。。。转折来的太突然。。。public static final class Tab {} 不是view,山穷水复疑无路,柳暗花明又一村。Tab里面还有这么几个View 或者 viewgroup:

TabLayout mParent;
TabView mView;
private View mCustomView;

发现TabView 获取不到,但是能够设置和获取到mCustomView,我们通过Android device monitor 查看布局

2017-07-02_221655.png

看到以下(1)对应的就是Tab,(2)对应的是我们设置的mCustomView

2017-07-02_221306.png

明显mCustomView的点击区域不能满足要求啊。。。怎么办,怎么没有显示TabView ,这里(1)的区域才是我们需要的,可能就是TabView 。我们知道 view.getparent()就可以获取到父view

2017-07-02_221358.png

还有第二个需求,就是不切换界面,mTabLayout.setupWithViewPager(mViewPager);这个会自动为我们关联tab并处理切换逻辑等,但是我们需要控制,所以不能设置这个,只能自己去实现tab 的点击效果,为了控制viewpaper左右滑动,发现并没有提供方法。。。。但是本质还是滑动事件的处理,重写onTouchEvent 返回true就可以了。

思路和解决方法有了,接下来就是具体实现了,具体看代码把。

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.philos.myandroidblogdemo.R;

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

/**
 * Created by Philos on 2017/6/24.
 */

public class TablayoutClickCheckActivity extends AppCompatActivity {

    private NoScrollViewPager mViewPager;
    private MyPagerAdapter mPagerAdapter;
    private TabLayout mTabLayout;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab_click_check);
        mViewPager = (NoScrollViewPager) findViewById(R.id.viewpaper);
        //禁止viewpaper滚动,通过设置setCurrentItem 来进行切换
        mViewPager.setScroll(false);
        mTabLayout = (TabLayout) findViewById(R.id.tab);

        //这里为了方便,直接new,在MyPagerAdapter的构造函数传进去
        final List<Fragment> viewList = new ArrayList<Fragment>();// 将要分页显示的View装入数组中
        for (int i = 0; i < 4; i++) {
            viewList.add(FragmentOne.getInstance(i));
        }

        mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), viewList);

        mViewPager.setOffscreenPageLimit(3);
        //监听切换事件,设置tab的选中和颜色
        mViewPager.addOnPageChangeListener(mOnPageChangeListener);

        mViewPager.setAdapter(mPagerAdapter);
        //为TabLayout设置ViewPager,这里不能这样设置了
//        mTabLayout.setupWithViewPager(mViewPager);

        //自定义tab的布局
        for (int i = 0; i < mPagerAdapter.getCount(); i++) {
            //setupWithViewPager 的话 tab 都帮我们初始化好了,但是没有就需要newTab
//            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            TabLayout.Tab tab = mTabLayout.newTab();
            if (tab != null) {
                tab.setCustomView(mPagerAdapter.getTabView(i));
                if (tab.getCustomView() != null) {
                    View tabView = (View) tab.getCustomView().getParent(); //重点是这一句
                    tabView.setTag(i);
                    tabView.setOnClickListener(mTabOnClickListener);
                }
            }
            //这里还需要自己加进去
            mTabLayout.addTab(tab, i);
        }
        //默认选中第一个
        setTabSelected(mTabLayout.getTabAt(0), 0, true);
    }

    public class MyPagerAdapter extends FragmentStatePagerAdapter {
        List<Fragment> mFragmentList;

        public MyPagerAdapter(FragmentManager fm, List<Fragment> list) {
            super(fm);
            this.mFragmentList = list;
            for (int i = 0; i < list.size(); i++) {
                TextView textView = new TextView(TablayoutClickCheckActivity.this);
                textView.setText("Tab" + (i + 1));
                mTabViewList.add(textView);
            }
        }

        @Override
        public int getCount() {
            return 4;
        }

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


        private List<View> mTabViewList = new ArrayList<View>();

        public View getTabView(int position) {
            return mTabViewList.get(position);
        }


        //重写这个方法,将设置每个Tab的标题
        @Override
        public CharSequence getPageTitle(int position) {
            return ((TextView) mTabViewList.get(position)).getText();
        }
    }


    ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
//            mSelectPos = position;
            setTabSelected(mTabLayout.getTabAt(position), position, true);
            int count = mTabLayout.getTabCount();
            for (int i = 0; i < count; i++) {
                if (i != position) {
                    setTabSelected(mTabLayout.getTabAt(i), i, false);
                }
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };


    private void setTabSelected(TabLayout.Tab tabAt, int position, boolean b) {
        TextView textView = ((TextView) tabAt.getCustomView());
        if (b)
            textView.setTextColor(Color.RED);
        else
            textView.setTextColor(Color.BLACK);
    }

    private boolean isAccountLogin = false;
    /**
     * 拦截TabLayout重设Tab点击事件,在点击“消息”或者“我”的tab时检查有没有登录,没有则跳登录页面
     */
    private View.OnClickListener mTabOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            int pos = (int) view.getTag();
            //没有登录时选中“消息”或者“我”的tab时跳登录页面
            if ((pos == 1 || pos == 2 || pos == 0) && !isAccountLogin) {
                new AlertDialog.Builder(TablayoutClickCheckActivity.this)
                        .setMessage("你还未登录,立即登录?").setTitle("提示").show();
                return;
            } else {
                TabLayout.Tab tab = mTabLayout.getTabAt(pos);
                if (tab != null) {
                    tab.select();
                }
                mViewPager.setCurrentItem(pos);
            }
        }
    };

}

布局文件activity_tab_click_check.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"
    android:orientation="vertical"
    android:background="#FFcccccc"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.philos.myandroidblogdemo.tablayout.NoScrollViewPager
        android:id="@+id/viewpaper"
        android:background="@color/colorAccent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        app:tabIndicatorHeight="0dp"
        app:tabMode="fixed"
        app:tabSelectedTextColor="#FF4081"
        app:tabTextColor="#000"
        android:background="#ffffff"></android.support.design.widget.TabLayout>

</LinearLayout>

可以控制滚动的ViewPaper NoScrollViewPager

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Created by Philos on 2017/7/2.
 */

public class NoScrollViewPager  extends ViewPager {
    private boolean isScroll;
    public NoScrollViewPager(Context context, AttributeSet attrs){
        super(context, attrs);
    }
    public NoScrollViewPager(Context context) {
        super(context);
    }


//    /**
//     * 1.dispatchTouchEvent一般情况不做处理
//     *,如果修改了默认的返回值,子孩子都无法收到事件
//     */
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        return super.dispatchTouchEvent(ev);   // return true;不行
//    }

    /**
     * 如果不需要嵌套之类的处理,不用处理这个情况
     * 是否拦截
     * 拦截:会走到自己的onTouchEvent方法里面来
     * 不拦截:事件传递给子孩子
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (isScroll){
            return super.onInterceptTouchEvent(ev);
        }else{
            return false;
        }
    }

    /**
     * 是否消费事件
     * 消费:事件就结束
     * 不消费:往父控件传
     */
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (isScroll){
            return super.onTouchEvent(ev);
        }else {
            return true;// 消费,拦截事件,就不会让
        }
    }


    public void setScroll(boolean scroll) {
        isScroll = scroll;
    }
}

FragmentOne

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.philos.myandroidblogdemo.R;

/**
 * Created by Philos on 2017/6/24.
 */

public class FragmentOne extends Fragment {

    private static final String EXTRA_KEY_TYPE = "EXTRA_KEY_TYPE";
    private int position = 0;

    private String[] titles = {"页面1", "页面2", "页面3", "页面4"};

    //因为四个fragment的布局一样只是中间的提示文字不一样,封装下用公用一个就可以了
    public static FragmentOne getInstance(int type){
        FragmentOne fragmentOne = new FragmentOne();
        Bundle bundle = new Bundle();
        bundle.putInt(EXTRA_KEY_TYPE, type);
        fragmentOne.setArguments(bundle);
        return fragmentOne;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Bundle bundle = getArguments();
        if (bundle != null) {
            position = bundle.getInt(EXTRA_KEY_TYPE, 0);
        }
        View view =  inflater.inflate(R.layout.fragment_one,container,false);
        TextView textView = (TextView) view.findViewById(R.id.text1);
        textView.setText(titles[position]);
        return view;
    }

}

fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:background="@color/colorAccent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".tablayout.FragmentOne">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="唐僧"
        android:layout_gravity="center"
        android:textSize="30sp"/>

</RelativeLayout>

作者:三也视界