Android 中仿支付宝城市服务功能

1、效果图展示

GIF.gif

2、实现思路

  • 实现配置:
    1)自定义的GridView
    2)自定义的TabLayout(需求中要求下划线比字体短)
    3)自定义的ScrollView

  • 实现流程:
    每一个Tag 标签对应着一个布局,也就是自定义的GridView(因为需要计算高度),把每一个Tag 标签布局对应着一层,计算每一层的高度,然后区分手势滑动以及通过TabLayout的Tab选择,在ScrollView中移动布局即可

3、自定义的TabLayout

EnhanceTabLayout.java
public class EnhanceTabLayout extends FrameLayout {
    private TabLayout mTabLayout;
    private List<String> mTabList;
    private List<View> mCustomViewList;
    private int mSelectIndicatorColor;
    private int mSelectTextColor;
    private int mUnSelectTextColor;
    private int mIndicatorHeight;
    private int mIndicatorWidth;
    private int mTabMode;
    private int mTabTextSize;

    public EnhanceTabLayout(@NonNull Context context) {
        super(context);
        init(context, null);
    }

    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void readAttr(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.EnhanceTabLayout);
        mSelectIndicatorColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabIndicatorColor, context.getResources().getColor(R.color.colorAccent));
        mUnSelectTextColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabTextColor, Color.parseColor("#666666"));
        mSelectTextColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabSelectTextColor, context.getResources().getColor(R.color.colorAccent));
        mIndicatorHeight = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabIndicatorHeight, 1);
        mIndicatorWidth = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabIndicatorWidth, 0);
        mTabTextSize = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabTextSize, 13);
        mTabMode = typedArray.getInt(R.styleable.EnhanceTabLayout_tab_Mode, 2);
        typedArray.recycle();
    }

    private void init(Context context, AttributeSet attrs) {
        readAttr(context, attrs);

        mTabList = new ArrayList<>();
        mCustomViewList = new ArrayList<>();
        View view = LayoutInflater.from(getContext()).inflate(R.layout.enhance_tab_layout, this, true);
        mTabLayout = (TabLayout) view.findViewById(R.id.enhance_tab_view);

        // 添加属性
        mTabLayout.setTabMode(mTabMode == 1 ? TabLayout.MODE_FIXED : TabLayout.MODE_SCROLLABLE);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                // onTabItemSelected(tab.getPosition());
                // Tab 选中之后,改变各个Tab的状态
                for (int i = 0; i < mTabLayout.getTabCount(); i++) {
                    View view = mTabLayout.getTabAt(i).getCustomView();
                    if (view == null) {
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    View indicator = view.findViewById(R.id.tab_item_indicator);
                    if (i == tab.getPosition()) { // 选中状态
                        text.setTextColor(mSelectTextColor);
                        indicator.setBackgroundColor(mSelectIndicatorColor);
                        indicator.setVisibility(View.VISIBLE);
                    } else {// 未选中状态
                        text.setTextColor(mUnSelectTextColor);
                        indicator.setVisibility(View.INVISIBLE);
                    }
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public List<View> getCustomViewList() {
        return mCustomViewList;
    }

    public void addOnTabSelectedListener(TabLayout.OnTabSelectedListener onTabSelectedListener) {
        mTabLayout.addOnTabSelectedListener(onTabSelectedListener);
    }

    /**
     * 与TabLayout 联动
     *
     * @param viewPager
     */
    public void setupWithViewPager(@Nullable ViewPager viewPager) {
        mTabLayout.addOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager, this));
    }


    /**
     * retrive TabLayout Instance
     *
     * @return
     */
    public TabLayout getTabLayout() {
        return mTabLayout;
    }

    /**
     * 添加tab
     *
     * @param tab
     */
    public void addTab(String tab) {
        mTabList.add(tab);
        View customView = getTabView(getContext(), tab, mIndicatorWidth, mIndicatorHeight, mTabTextSize);
        mCustomViewList.add(customView);
        mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
    }

    public static class ViewPagerOnTabSelectedListener implements TabLayout.OnTabSelectedListener {

        private final ViewPager mViewPager;
        private final WeakReference<EnhanceTabLayout> mTabLayoutRef;

        public ViewPagerOnTabSelectedListener(ViewPager viewPager, EnhanceTabLayout enhanceTabLayout) {
            mViewPager = viewPager;
            mTabLayoutRef = new WeakReference<EnhanceTabLayout>(enhanceTabLayout);
        }

        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
            EnhanceTabLayout mTabLayout = mTabLayoutRef.get();
            if (mTabLayoutRef != null) {
                List<View> customViewList = mTabLayout.getCustomViewList();
                if (customViewList == null || customViewList.size() == 0) {
                    return;
                }
                for (int i = 0; i < customViewList.size(); i++) {
                    View view = customViewList.get(i);
                    if (view == null) {
                        return;
                    }
                    TextView text = (TextView) view.findViewById(R.id.tab_item_text);
                    View indicator = view.findViewById(R.id.tab_item_indicator);
                    if (i == tab.getPosition()) { // 选中状态
                        text.setTextColor(mTabLayout.mSelectTextColor);
                        indicator.setBackgroundColor(mTabLayout.mSelectIndicatorColor);
                        indicator.setVisibility(View.VISIBLE);
                    } else {// 未选中状态
                        text.setTextColor(mTabLayout.mUnSelectTextColor);
                        indicator.setVisibility(View.INVISIBLE);
                    }
                }
            }

        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            // No-op
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
            // No-op
        }
    }

    /**
     * 获取Tab 显示的内容
     *
     * @param context
     * @param
     * @return
     */
    public static View getTabView(Context context, String text, int indicatorWidth, int indicatorHeight, int textSize) {
        View view = LayoutInflater.from(context).inflate(R.layout.tab_item_layout, null);
        TextView tabText = (TextView) view.findViewById(R.id.tab_item_text);
        if (indicatorWidth > 0) {
            View indicator = view.findViewById(R.id.tab_item_indicator);
            ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams();
            layoutParams.width = indicatorWidth;
            layoutParams.height = indicatorHeight;
            indicator.setLayoutParams(layoutParams);
        }
        tabText.setTextSize(textSize);
        tabText.setText(text);
        return view;
    }

}
tab_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tab_item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/x50"
        android:text="首页"
        android:textColor="#7DD8FE"
        />
    <View
        android:id="@+id/tab_item_indicator"
        android:layout_width="10dp"
        android:layout_height="2dp"
        android:layout_marginTop="5dp"
        android:background="@color/colorAccent"
        android:visibility="invisible"
        />
</LinearLayout>
enhance_tab_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/enhance_tab_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorHeight="0dp"
        app:tabMaxWidth="0dp"
        app:tabMode="fixed"
        app:tabGravity="fill"
        >
    </android.support.design.widget.TabLayout>
</FrameLayout>
styleable.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>


    <declare-styleable name="EnhanceTabLayout">
        <attr name="tab_Mode" format="enum">
            <enum name="mode_fixed" value="1"/>
            <enum name="mode_scrollable" value="2"/>
        </attr>
        <attr name="tabIndicatorColor" format="color"/>
        <attr name="tabSelectTextColor" format="color"/>
        <attr name="tabTextColor" format="color"/>
        <attr name="tabIndicatorHeight" format="dimension"/>
        <attr name="tabIndicatorWidth" format="dimension"/>
        <attr name="tabTextSize" format="dimension"/>
    </declare-styleable>
</resources>

4、自定义的GridView

MyGridView.java
public class MyGridView extends GridView {
    public MyGridView(android.content.Context context,
                      android.util.AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 设置不滚动
     */
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);

    }

}

5、自定义的ScrollView

ObservableScrollView.java
public class ObservableScrollView extends ScrollView {
    private ScrollViewListener scrollViewListener = null;
    public ObservableScrollView(Context context) {
        super(context);
    }
    public ObservableScrollView(Context context, AttributeSet attrs,
                                int defStyle) {
        super(context, attrs, defStyle);
    }
    public ObservableScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }
    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
        }
    }
    public interface ScrollViewListener {
        void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy);
    }
}

6、完整实现代码如下

item_function_content_first.xml、 item_function_content_second.xml、item_function_content_third.xml、item_function_content_fourth.xml的布局代码基本是一样,不过需要注意的是:最后一层加了一个有高度的空布局

item_function_content_first.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/c_black_02"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/tv_ss_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/dimen_5"
        android:layout_marginStart="@dimen/dimen_10"
        android:layout_marginTop="@dimen/x20"
        android:drawablePadding="@dimen/x10"
        android:drawableStart="@drawable/ic_blue_left"
        android:text="@string/ss_card_insurance"
        android:textColor="@color/c_gray_02"
        android:textSize="@dimen/x40" />

    <tecsun.jx.yt.phone.widget.MyGridView
        android:id="@+id/gv_home_ss_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:numColumns="4"
        android:padding="@dimen/dimen_10" />

</LinearLayout>
item_function_content_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/c_black_02"
    android:orientation="vertical"
    >


    <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="@dimen/dimen_5"
    android:layout_marginStart="@dimen/dimen_10"
    android:layout_marginTop="@dimen/x20"
    android:drawablePadding="@dimen/x10"
    android:drawableStart="@drawable/ic_blue_left"
    android:text="@string/labor_relations"
    android:textColor="@color/c_gray_02"
    android:textSize="@dimen/x40" />

    <tecsun.jx.yt.phone.widget.MyGridView
    android:id="@+id/gv_home_labor_relations"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:numColumns="4"
    android:padding="@dimen/dimen_10" />


</LinearLayout>
item_function_content_third.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/c_black_02"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/tv_ss_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/dimen_5"
        android:layout_marginStart="@dimen/dimen_10"
        android:layout_marginTop="@dimen/x20"
        android:drawablePadding="@dimen/x10"
        android:drawableStart="@drawable/ic_blue_left"
        android:text="@string/personnel_talent"
        android:textColor="@color/c_gray_02"
        android:textSize="@dimen/x40" />

    <tecsun.jx.yt.phone.widget.MyGridView
        android:id="@+id/gv_home_personnel_talent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:numColumns="4"
        android:padding="@dimen/dimen_10" />

</LinearLayout>
item_function_content_fourth.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/c_black_02"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/tv_ss_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/dimen_5"
        android:layout_marginStart="@dimen/dimen_10"
        android:layout_marginTop="@dimen/x20"
        android:drawablePadding="@dimen/x10"
        android:drawableStart="@drawable/ic_blue_left"
        android:text="@string/employment_business"
        android:textColor="@color/c_gray_02"
        android:textSize="@dimen/x40" />

    <tecsun.jx.yt.phone.widget.MyGridView
        android:id="@+id/gv_home_employment_business"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:numColumns="4"
        android:padding="@dimen/dimen_10" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="450dp">

    </LinearLayout>

</LinearLayout>
主布局代码:tab_main_funtion_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/c_black_02"
    android:orientation="vertical">

    <View
        android:id="@+id/head_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/c_24ade4"
        />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/c_24ade4"
        >

        <tecsun.jx.yt.phone.widget.EnhanceTabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            app:tabIndicatorHeight="2dp"
            app:tabIndicatorWidth="20dp"
            app:tabTextColor="#7DD8FE"
            app:tab_Mode="mode_fixed"
            app:tabSelectTextColor="@color/c_white"
            app:tabIndicatorColor="@color/c_white"
            app:tabTextSize="5sp"
            >

        </tecsun.jx.yt.phone.widget.EnhanceTabLayout>

        <FrameLayout
            android:id="@+id/wrapperFl"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>
    </FrameLayout>
    <tecsun.jx.yt.phone.widget.ObservableScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:id="@+id/containerLl"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
        </LinearLayout>
    </tecsun.jx.yt.phone.widget.ObservableScrollView>


</LinearLayout>
主界面实现代码:tab_main_funtion_fragment.xml
public class TabMainFuntionFragment extends Fragment implements ObservableScrollView.ScrollViewListener{

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

    /**
     * requestCode——读写外部存储权限
     */
    private static final int REQUEST_CODE_STORAGE = 0x02;
    private static final int REQUEST_CODE_STORAGE_VOICE = 0x05;
    private View homeRootView;
    private GridView mGv01, mGv02, mGv03, mGv04;
    private TextView tvSsCard;
    private Context mContext;
    private ApplyCardParam applyCardParam;
    private String accountId;
    private String accountName;


    private FrameLayout wrapperFl;
    private EnhanceTabLayout tabLayout;
    private ObservableScrollView scrollView;
    private LinearLayout containerLl;
    private boolean firstAlreadyInflated = true;
    private ViewGroup firstFloorVg;
    private ViewGroup secondFloorVg;
    private ViewGroup thirdFloorVg;
    private ViewGroup fourthFloorVg;
    private int secondFloorVgPositionDistance;//第二层滑动至顶部的距离
    private int thirdFloorVgPositionDistance;
    private int fourthFloorVgPositionDistance;
    private int currentPosition = 0;
    private boolean tabInterceptTouchEventTag = true;//标志位,用来区分是点击了tab还是手动滑动scrollview

    private String url = "";
    private String title = "";
    private int paddingRight;
    private int paddingLeft;
    private View headView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {
        LogUtils.d("onCreateView=============");
        homeRootView = inflater.inflate(R.layout.tab_main_funtion_fragment, container, false);
        mContext =  getActivity();

        initViews(homeRootView);
        initListeners();
        initSSCardBusinessListene();
        initLaborRelations();
        initpersonnelTalent();
        initemploymentBusiness();
        return homeRootView;
    }

    private void setFunctionIndexFromHomeFragment(){
        MainActivity activity = (MainActivity) getActivity();
        boolean isOnclickFunc = activity.isOnclickFunc;
        int funcIndex = activity.funcIndex;
        currentPosition = funcIndex;
        LogUtils.d("setFunctionIndexFromHomeFragment========currentPosition============="+currentPosition);
        LogUtils.d("isOnclickFunc============="+isOnclickFunc);
        LogUtils.d("funcIndex============="+funcIndex);

        smoothScrollByPositon(currentPosition);
    }

    private void setHomeFragmentFunctionIndex(int position){
        MainActivity activity = (MainActivity) getActivity();
        activity.funcIndex = position;
        currentPosition = position;
    }



    private void initViews(View view) {
        headView = (View)view.findViewById(R.id.head_view);
        wrapperFl = (FrameLayout)view.findViewById(R.id.wrapperFl);
        tabLayout = (EnhanceTabLayout)view.findViewById(R.id.tabLayout);
        scrollView = (ObservableScrollView)view.findViewById(R.id.scrollView);
        containerLl = (LinearLayout)view.findViewById(R.id.containerLl);

        tabLayout.addTab("社会保险");
        tabLayout.addTab("劳动关系");
        tabLayout.addTab("人事人才");
        tabLayout.addTab("就业创业");


        firstFloorVg = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.item_function_content_first, null);
        secondFloorVg = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.item_function_content_second, null);
        thirdFloorVg = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.item_function_content_third, null);
        fourthFloorVg = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.item_function_content_fourth, null);
        fourthFloorVg.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        containerLl.addView(firstFloorVg);
        containerLl.addView(secondFloorVg);
        containerLl.addView(thirdFloorVg);
        containerLl.addView(fourthFloorVg);

        mGv01 = (GridView)firstFloorVg.findViewById(R.id.gv_home_ss_card);
        mGv02 = (GridView)secondFloorVg.findViewById(R.id.gv_home_labor_relations);
        mGv03 = (GridView)thirdFloorVg.findViewById(R.id.gv_home_personnel_talent);
        mGv04 = (GridView)fourthFloorVg.findViewById(R.id.gv_home_employment_business);


    }


    private void initListeners() {
        wrapperFl.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LogUtils.d("wrapperFl onTouch");
                tabInterceptTouchEventTag = true;//让tab来处理滑动
                return false;
            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentPosition = tab.getPosition();
                if(!tabInterceptTouchEventTag){//手动滑动页面时则不再次处理滑动
                    return;
                }
                scrollView.computeScroll();

                smoothScrollByPositon(currentPosition);

            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
        scrollView.setScrollViewListener(this);
        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LogUtils.d("scrollView onTouch");
                tabInterceptTouchEventTag = false;//让scrollview处理滑动
                return false;
            }
        });

    }

    private void smoothScrollByPositon(int currentPosition){
        LogUtils.d("smoothScrollByPositon===============");
        switch (currentPosition) {
            case 0:
                scrollView.smoothScrollTo(0, 0);
                tabLayout.getTabLayout().getTabAt(0).select();
                setHomeFragmentFunctionIndex(0);
                break;
            case 1:
                scrollView.smoothScrollTo(0, secondFloorVgPositionDistance);
                tabLayout.getTabLayout().getTabAt(1).select();
                setHomeFragmentFunctionIndex(1);
                break;
            case 2:
                scrollView.smoothScrollTo(0, thirdFloorVgPositionDistance);
                tabLayout.getTabLayout().getTabAt(2).select();
                setHomeFragmentFunctionIndex(2);
                break;
            case 3:
                scrollView.smoothScrollTo(0, fourthFloorVgPositionDistance);
                tabLayout.getTabLayout().getTabAt(3).select();
                setHomeFragmentFunctionIndex(3);
                break;
            default:
                break;
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtils.d("setUserVisibleHint=============");
        LogUtils.d("setUserVisibleHint=============isVisibleToUser========"+isVisibleToUser);
        try {
            if (isVisibleToUser){
                if (firstAlreadyInflated) {//获取各层离screen顶部的位置以及计算滑动值相应顶部所需要的距离
                    firstAlreadyInflated = false;
                    int[] firstFloorVgPosition = new int[2];
                    int[] secondFloorVgPosition = new int[2];
                    int[] thirdFloorVgPosition = new int[2];
                    int[] fourthFloorVgPosition = new int[2];
                    firstFloorVg.getLocationOnScreen(firstFloorVgPosition);
                    secondFloorVg.getLocationOnScreen(secondFloorVgPosition);
                    thirdFloorVg.getLocationOnScreen(thirdFloorVgPosition);
                    fourthFloorVg.getLocationOnScreen(fourthFloorVgPosition);
                    int firstFloorVgPositionAnchor = firstFloorVgPosition[1];
                    int secondFloorVgPositionAnchor = secondFloorVgPosition[1];
                    int thirdFloorVgPositionAnchor = thirdFloorVgPosition[1];
                    int fourthFloorVgPositionAnchor = fourthFloorVgPosition[1];
                    Log.d(TAG, "第一层距离屏幕的firstFloorVgPosition[0]距离是:" + firstFloorVgPosition[0]);
                    Log.d(TAG, "第一层距离屏幕的距离是:" + firstFloorVgPosition[1]);
                    Log.d(TAG, "第一层距离屏幕的secondFloorVgPosition[0]距离是:" + secondFloorVgPosition[0]);
                    Log.d(TAG, "第二层距离屏幕的距离是:" + secondFloorVgPosition[1]);
                    Log.d(TAG, "第一层距离屏幕的thirdFloorVgPosition[0]距离是:" + thirdFloorVgPosition[0]);
                    Log.d(TAG, "第三层距离屏幕的距离是:" + thirdFloorVgPosition[1]);
                    Log.d(TAG, "第一层距离屏幕的fourthFloorVgPosition[0]距离是:" + fourthFloorVgPosition[0]);
                    Log.d(TAG, "第四层距离屏幕的距离是:" + fourthFloorVgPosition[1]);
                    secondFloorVgPositionDistance = secondFloorVgPositionAnchor - firstFloorVgPositionAnchor;
                    thirdFloorVgPositionDistance = thirdFloorVgPositionAnchor - firstFloorVgPositionAnchor;
                    fourthFloorVgPositionDistance = fourthFloorVgPositionAnchor - firstFloorVgPositionAnchor;

                    Log.d(TAG, "secondFloorVgPositionDistance距离是:" + secondFloorVgPositionDistance);
                    Log.d(TAG, "thirdFloorVgPositionDistance距离是:" + thirdFloorVgPositionDistance);
                    Log.d(TAG, "fourthFloorVgPositionDistance距离是:" + fourthFloorVgPositionDistance);
                }

                setFunctionIndexFromHomeFragment();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        Log.d(TAG, "onScrollChanged=====================");
        Log.d(TAG, "onScrollChanged===========currentPosition=========="+currentPosition);
        Log.d(TAG, "onScrollChanged============tabInterceptTouchEventTag========="+tabInterceptTouchEventTag);
        if (tabInterceptTouchEventTag) {//让tab来处理滑动
            return;
        }
        Log.d(TAG, "当前scrollView的位置——>" + y);
        if (y < secondFloorVgPositionDistance) {
            if (currentPosition != 0) {
                scrollView.computeScroll();
                tabLayout.getTabLayout().getTabAt(0).select();
                setHomeFragmentFunctionIndex(0);
            }
        } else if (y < thirdFloorVgPositionDistance) {
            if (currentPosition != 1) {
                scrollView.computeScroll();
                tabLayout.getTabLayout().getTabAt(1).select();
                setHomeFragmentFunctionIndex(1);
            }
        } else if (y < fourthFloorVgPositionDistance) {
            if (currentPosition != 2) {
                scrollView.computeScroll();
                tabLayout.getTabLayout().getTabAt(2).select();
                setHomeFragmentFunctionIndex(2);
            }
        } else {
            Log.d(TAG, "onScrollChanged==================currentPosition====================="+currentPosition);
            if (currentPosition != 3) {
                scrollView.computeScroll();
                tabLayout.getTabLayout().getTabAt(3).select();
                setHomeFragmentFunctionIndex(3);
            }
        }
    }


 


    //社保服务
    private void initSSCardBusinessListene() {
        final String[] arrNames = getResources().getStringArray(R.array.funtion_ss_card_business);
        int[] arrIcons = ViewUtils.getArrayDrawable(getActivity(), R.array.funtion_ss_card_business_icons);
        if (arrNames.length > 0) {
            HomeOptionAdapter adapter = new HomeOptionAdapter(getActivity(), arrIcons, arrNames);
            mGv01.setAdapter(adapter);
        }

        mGv01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               //to do
            }
        });
    }


    //劳动关系
    private void initLaborRelations() {
        String[] arrNames = getResources().getStringArray(R.array.funtion_ss_labor_relations);
        int[] arrIcons = ViewUtils.getArrayDrawable(getActivity(), R.array.funtion_ss_labor_relations_icons);
        if (arrNames.length > 0) {
            HomeOptionAdapter adapter = new HomeOptionAdapter(getActivity(), arrIcons, arrNames);
            mGv02.setAdapter(adapter);
        }

        mGv02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
               //to do
            }
        });


    }

    //人事人才
    private void initpersonnelTalent() {
        String[] arrNames = getResources().getStringArray(R.array.funtion_ss_personnel_talent);
        int[] arrIcons = ViewUtils.getArrayDrawable(getActivity(), R.array.funtion_ss_personnel_talent_icons);
        if (arrNames.length > 0) {
            HomeOptionAdapter adapter = new HomeOptionAdapter(getActivity(), arrIcons, arrNames);
            mGv03.setAdapter(adapter);
        }

        mGv03.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
               //to do
            }
        });

    }

    //就业创业
    private void initemploymentBusiness() {
        String[] arrNames = getResources().getStringArray(R.array.funtion_ss_employment_business);
        int[] arrIcons = ViewUtils.getArrayDrawable(getActivity(), R.array.funtion_ss_employment_business_icons);
        if (arrNames.length > 0) {
            HomeOptionAdapter adapter = new HomeOptionAdapter(getActivity(), arrIcons, arrNames);
            mGv04.setAdapter(adapter);
        }

        mGv04.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
               //to do
            }
        });


    }


 

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.d("onResume======================");
        ViewGroup.LayoutParams params = headView.getLayoutParams();
        LogUtils.d("params.height======================"+params.height);
        LogUtils.d("params.width======================"+params.width);
        int mStatusBarHeight = getStatusBarHeight();

        LogUtils.d("mStatusBarHeight======================"+mStatusBarHeight);
        params.height = mStatusBarHeight;
        headView.setLayoutParams(params);
    }

    private int getStatusBarHeight() {
        Resources resources = getActivity().getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen","android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }


    @Override
    public void onPause() {
        super.onPause();
        LogUtils.d("onPause======================");
    }
}

应该涉及到了ViewPager两个Fragment之间的切换和通信,如下所示:


image.png
image.png

通过TabMainFuntionFragment和 TabMainHomeFragment 它们的依赖容器 MainActivity,实现值传递,配置如下所示:

TabMainFuntionFragment.java
 private void setFunctionIndexFromHomeFragment(){
        MainActivity activity = (MainActivity) getActivity();
        boolean isOnclickFunc = activity.isOnclickFunc;
        int funcIndex = activity.funcIndex;
        currentPosition = funcIndex;
        LogUtils.d("setFunctionIndexFromHomeFragment========currentPosition============="+currentPosition);
        LogUtils.d("isOnclickFunc============="+isOnclickFunc);
        LogUtils.d("funcIndex============="+funcIndex);
        smoothScrollByPositon(currentPosition);
    }
TabMainHomeFragment.java
    private void jumpToTabMainFunctionFragment(int position){
        LogUtils.d("jumpToTabMainFunctionFragment===================");
        MainActivity activity = (MainActivity) getActivity();
        activity.funcIndex = position;
        activity.isOnclickFunc = true;
        LogUtils.d("activity.funcIndex==================="+activity.funcIndex);
        LogUtils.d("activity.isOnclickFunc==================="+activity.isOnclickFunc);
        activity.mViewPager.setCurrentItem(1);
    }

MainActivity.java
    public int funcIndex = 0;
    public boolean isOnclickFunc = false;

7、参考博文如下

https://www.2cto.com/kf/201803/731497.html

https://www.jianshu.com/p/30128dcfedd4

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,732评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,496评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,264评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,807评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,806评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,675评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,029评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,683评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,704评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,666评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,773评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,413评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,016评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,204评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,083评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,503评论 2 343

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,449评论 25 707
  • 原文章地址 Google官方在14年 I/O大会上推出了全新的设计语言——Material Design, Mat...
    菜菜编程阅读 2,636评论 0 6
  • 我有抽烟的恶习,却从没有从抽烟中得到过什么好处。 可是还是要抽,执着的蹲在垃圾桶旁边,执着的蹲在空无一人的楼道,吞...
    马朱朱阅读 269评论 0 0
  • 壹点…… 壹点·爱·喜悲 壹点·亲·甜苦 壹点·梦·实虚 壹点·男·坏好 壹点·女·物心 壹点·人·假面 壹点·恶...
    成琦言凡阅读 165评论 0 0
  • 记得去年冬天,我在朋友圈里看到一个朋友发表的快手分享,隐隐约约依稀有点面熟,心里有点疑惑。带着满腹的疑虑,我在百...
    点到_790b阅读 463评论 0 2