示例代码中的 SlidingTabLayout 简单使用(二)

SlidingTabLayout底部选项卡水平居中(系列2) 找到Android SlidingTabLayout源代码,在Android SlidingTabLayout源代码中有一个方法: private void populateTabStrip(); 这是谷歌官方实现的Android SlidingTabLayout添加底部选项卡Tab的代码,如果为了实现前文所述的将Tab均分水平位置空间,则需要修改此方法,在此方法中添加如下代码:Lin 阅读详情

在《示例代码中的 SlidingTabLayout 简单使用(一)》中还有些不足,如:选择器高度过高,底部有阴影,默认的加粗文本等。修改示例中的两个类的部分代码,效果如下:


对已选择的选项卡应用的纯白色,而对其他的选项卡应用了 60% 的白色。


MainActivity.java 的代码未变,如上一篇所示;


content_main.xml: 修改了 SlidingTabLayout 的背景颜色:

android:background="@color/primaryGreen"



 SlidingTabStrip.java 内部只更新了常量值 :

// 修改后会降低选择器的高度并移除阴影
    private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
    private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 2;


SlidingTabLayout.java (修改的地方不多,如下文有中文注释的地方就有修改):

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.crazy.tabs;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.TextView;

/**
 * To be used with ViewPager to provide a tab indicator component which give constant feedback as to
 * the user's scroll progress.
 * <p>
 * To use the component, simply add it to your view hierarchy. Then in your
 * {@link android.app.Activity} or {@link android.support.v4.app.Fragment} call
 * {@link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for.
 * <p>
 * The colors can be customized in two ways. The first and simplest is to provide an array of colors
 * via {@link #setSelectedIndicatorColors(int...)} and {@link #setDividerColors(int...)}. The
 * alternative is via the {@link TabColorizer} interface which provides you complete control over
 * which color is used for any individual position.
 * <p>
 * The views used as tabs can be customized by calling {@link #setCustomTabView(int, int)},
 * providing the layout ID of your custom layout.
 */
public class SlidingTabLayout extends HorizontalScrollView {

    /**
     * Allows complete control over the colors drawn in the tab layout. Set with
     * {@link #setCustomTabColorizer(TabColorizer)}.
     */
    public interface TabColorizer {

        /**
         * @return return the color of the indicator used when {@code position} is selected.
         */
        int getIndicatorColor(int position);

        /**
         * @return return the color of the divider drawn to the right of {@code position}.
         */
        int getDividerColor(int position);

    }

    private static final int TITLE_OFFSET_DIPS = 24;
    private static final int TAB_VIEW_PADDING_DIPS = 16;
    private static final int TAB_VIEW_TEXT_SIZE_SP = 12;

    private int mTitleOffset;

    private int mTabViewLayoutId;
    private int mTabViewTextViewId;

    // 定义两种需要添加的选项卡颜色
    private int mDefaultTextColor;
    private int mSelectedTextColor;

    private ViewPager mViewPager;
    private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;

    private final SlidingTabStrip mTabStrip;

    public SlidingTabLayout(Context context) {
        this(context, null);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // 获取选项卡颜色,如果未定义的话,则使用主题默认的颜色
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.SlidingTabLayout);
        int defaultTextColor = a.getColor(
                R.styleable.SlidingTabLayout_android_textColorPrimary, 0);
        mDefaultTextColor = a.getColor(
                R.styleable.SlidingTabLayout_textColorTabDefault, defaultTextColor);
        mSelectedTextColor = a.getColor(
                R.styleable.SlidingTabLayout_textColorTabSelected ,defaultTextColor);
        a.recycle();
        

        // Disable the Scroll Bar
        setHorizontalScrollBarEnabled(false);
        // Make sure that the Tab Strips fills this View
        setFillViewport(true);

        mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);

        mTabStrip = new SlidingTabStrip(context);
        addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }


    // 在每次选项改变时更新选项卡文本颜色的新方法
    private void updateSelectedTitle(int position) {
        final PagerAdapter adapter = mViewPager.getAdapter();
        for (int i = 0; i < adapter.getCount(); i++) {
            final View tabView = mTabStrip.getChildAt(i);
            if (TextView.class.isInstance(tabView)) {
                TextView titleView = (TextView)tabView;
                boolean isSelected = i == position;
                titleView.setTextColor(isSelected ? mSelectedTextColor : mDefaultTextColor);
            }
        }
    }

    /**
     * Set the custom {@link TabColorizer} to be used.
     *
     * If you only require simple custmisation then you can use
     * {@link #setSelectedIndicatorColors(int...)} and {@link #setDividerColors(int...)} to achieve
     * similar effects.
     */
    public void setCustomTabColorizer(TabColorizer tabColorizer) {
        mTabStrip.setCustomTabColorizer(tabColorizer);
    }

    /**
     * Sets the colors to be used for indicating the selected tab. These colors are treated as a
     * circular array. Providing one color will mean that all tabs are indicated with the same color.
     */
    public void setSelectedIndicatorColors(int... colors) {
        mTabStrip.setSelectedIndicatorColors(colors);
    }

    /**
     * Sets the colors to be used for tab dividers. These colors are treated as a circular array.
     * Providing one color will mean that all tabs are indicated with the same color.
     */
    public void setDividerColors(int... colors) {
        mTabStrip.setDividerColors(colors);
    }

    /**
     * Set the {@link ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
     * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so
     * that the layout can update it's scroll position correctly.
     *
     * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
     */
    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mViewPagerPageChangeListener = listener;
    }

    /**
     * Set the custom layout to be inflated for the tab views.
     *
     * @param layoutResId Layout id to be inflated
     * @param textViewId id of the {@link TextView} in the inflated view
     */
    public void setCustomTabView(int layoutResId, int textViewId) {
        mTabViewLayoutId = layoutResId;
        mTabViewTextViewId = textViewId;
    }

    /**
     * Sets the associated view pager. Note that the assumption here is that the pager content
     * (number of tabs and tab titles) does not change after this call has been made.
     */
    public void setViewPager(ViewPager viewPager) {
        mTabStrip.removeAllViews();

        mViewPager = viewPager;
        if (viewPager != null) {
            viewPager.setOnPageChangeListener(new InternalViewPagerListener());
            populateTabStrip();
        }
    }

    /**
     * Create a default view to be used for tabs. This is called if a custom tab view is not set via
     * {@link #setCustomTabView(int, int)}.
     */
    protected TextView createDefaultTabView(Context context) {
        TextView textView = new TextView(context);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
        textView.setTypeface(Typeface.DEFAULT_BOLD);

        // 这会移除 Holo 的默认背景强调以及选项卡的粗体文本
      //  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // If we're running on Honeycomb or newer, then we can use the Theme's
            // selectableItemBackground to ensure that the View has a pressed state
     //       TypedValue outValue = new TypedValue();
     //       getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
     //               outValue, true);
     //       textView.setBackgroundResource(outValue.resourceId);
     //   }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            // If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
            textView.setAllCaps(true);
        }

        int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
        textView.setPadding(padding, padding, padding, padding);

        return textView;
    }

    private void populateTabStrip() {
        final PagerAdapter adapter = mViewPager.getAdapter();
        final OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set, try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
                        false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);

            mTabStrip.addView(tabView);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (mViewPager != null) {
            scrollToTab(mViewPager.getCurrentItem(), 0);
        }
    }

    private void scrollToTab(int tabIndex, int positionOffset) {
        final int tabStripChildCount = mTabStrip.getChildCount();
        if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
            return;
        }

        View selectedChild = mTabStrip.getChildAt(tabIndex);
        if (selectedChild != null) {

            // 调用在每次选项改变时更新文本颜色的新方案
            updateSelectedTitle(tabIndex);
            
            
            int targetScrollX = selectedChild.getLeft() + positionOffset;

            if (tabIndex > 0 || positionOffset > 0) {
                // If we're not at the first child and are mid-scroll, make sure we obey the offset
                targetScrollX -= mTitleOffset;
            }

            scrollTo(targetScrollX, 0);
        }
    }

    private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
        private int mScrollState;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int tabStripChildCount = mTabStrip.getChildCount();
            if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
                return;
            }

            mTabStrip.onViewPagerPageChanged(position, positionOffset);

            View selectedTitle = mTabStrip.getChildAt(position);
            int extraOffset = (selectedTitle != null)
                    ? (int) (positionOffset * selectedTitle.getWidth())
                    : 0;
            scrollToTab(position, extraOffset);

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
                        positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            mScrollState = state;

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
                mTabStrip.onViewPagerPageChanged(position, 0f);
                scrollToTab(position, 0);
            }

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageSelected(position);
            }
        }

    }

    private class TabClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                if (v == mTabStrip.getChildAt(i)) {
                    mViewPager.setCurrentItem(i);
                    return;
                }
            }
        }
    }

}



对应的资源文件:


attrs.xml :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SlidingTabLayout">
        <attr name="android:textColorPrimary" />
        <attr name="textColorTabDefault" format="color" />
        <attr name="textColorTabSelected" format="color" />
    </declare-styleable>
</resources>



styles.xml:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/primaryGreen</item>
        <item name="colorPrimaryDark">@color/darkGreen</item>
        <item name="colorAccent">@color/accentGreen</item>
        
        <!--移除 ActionBar 的阴影-->
        <item name="android:windowContentOverlay">@null</item>
        
        <!--选项卡的颜色属性-->
        <item name="textColorTabDefault">@color/tabTextDefault</item>
        <item name="textColorTabSelected">@color/tabTextSelected</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>


colors.xml :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <!--定义的颜色-->
    <color name="accentGreen" >#d0f8ce</color>
    <color name="darkGreen" >#0a7e07</color>
    <color name="primaryGreen">#259b24</color>
    <color name="tabTextDefault" >#99ffffff</color>
    <color name="tabTextSelected" >#ffffff</color>
</resources>







由于在后面用到了 标题水平居中的情况,而在上面的改动中并没有增加相应的代码,现在增加了相应代码的 SlindingTabLayout 类:

package com.scxh.listlayout;

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Build;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * To be used with ViewPager to provide a tab indicator component which give constant feedback as to
 * the user's scroll progress.
 * <p/>
 * To use the component, simply add it to your view hierarchy. Then in your
 * {@link android.app.Activity} or {@link android.support.v4.app.Fragment} call
 * {@link #setViewPager(ViewPager)} providing it the ViewPager this layout is being used for.
 * <p/>
 * The colors can be customized in two ways. The first and simplest is to provide an array of colors
 * via {@link #setSelectedIndicatorColors(int...)} and {@link #setDividerColors(int...)}. The
 * alternative is via the {@link TabColorizer} interface which provides you complete control over
 * which color is used for any individual position.
 * <p/>
 * The views used as tabs can be customized by calling {@link #setCustomTabView(int, int)},
 * providing the layout ID of your custom layout.
 */
public class SlidingTabLayout extends HorizontalScrollView {

    /**
     * Allows complete control over the colors drawn in the tab layout. Set with
     * {@link #setCustomTabColorizer(TabColorizer)}.
     */
    public interface TabColorizer {

        /**
         * @return return the color of the indicator used when {@code position} is selected.
         */
        int getIndicatorColor(int position);

        /**
         * @return return the color of the divider drawn to the right of {@code position}.
         */
        int getDividerColor(int position);

    }

    private static final int TITLE_OFFSET_DIPS = 24;
    private static final int TAB_VIEW_PADDING_DIPS = 16;
    private static final int TAB_VIEW_TEXT_SIZE_SP = 12;

    private int mTitleOffset;

    private int mTabViewLayoutId;
    private int mTabViewTextViewId;

    // 定义两种需要添加的选项卡颜色
    private int mDefaultTextColor;
    private int mSelectedTextColor;
    // =============================== 以上 =========

    private ViewPager mViewPager;
    private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;

    private final SlidingTabStrip mTabStrip;

    public SlidingTabLayout(Context context) {
        this(context, null);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SlidingTabLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        // 获取选项卡颜色,如果未定义的话,则使用主题默认的颜色
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.SlidingTabLayout);
        int defaultTextColor = a.getColor(
                R.styleable.SlidingTabLayout_android_textColorPrimary, 0);
        mDefaultTextColor = a.getColor(
                R.styleable.SlidingTabLayout_textColorTabDefault, defaultTextColor);
        mSelectedTextColor = a.getColor(
                R.styleable.SlidingTabLayout_textColorTabSelected, defaultTextColor);
        a.recycle();
        // =============================== 以上 =========


        // Disable the Scroll Bar
        setHorizontalScrollBarEnabled(false);
        // Make sure that the Tab Strips fills this View
        setFillViewport(true);

        mTitleOffset = (int) (TITLE_OFFSET_DIPS * getResources().getDisplayMetrics().density);

        mTabStrip = new SlidingTabStrip(context);
        addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }


    // 在每次选项改变时更新选项卡文本颜色的新方法
    private void updateSelectedTitle(int position) {
        final PagerAdapter adapter = mViewPager.getAdapter();
        for (int i = 0; i < adapter.getCount(); i++) {
            final View tabView = mTabStrip.getChildAt(i);
            if (TextView.class.isInstance(tabView)) {
                TextView titleView = (TextView) tabView;
                boolean isSelected = i == position;
                titleView.setTextColor(isSelected ? mSelectedTextColor : mDefaultTextColor);
            }
        }
    }
    // =============================== 以上 =========

    /**
     * Set the custom {@link TabColorizer} to be used.
     * <p/>
     * If you only require simple custmisation then you can use
     * {@link #setSelectedIndicatorColors(int...)} and {@link #setDividerColors(int...)} to achieve
     * similar effects.
     */
    public void setCustomTabColorizer(TabColorizer tabColorizer) {
        mTabStrip.setCustomTabColorizer(tabColorizer);
    }

    /**
     * Sets the colors to be used for indicating the selected tab. These colors are treated as a
     * circular array. Providing one color will mean that all tabs are indicated with the same color.
     */
    public void setSelectedIndicatorColors(int... colors) {
        mTabStrip.setSelectedIndicatorColors(colors);
    }

    /**
     * Sets the colors to be used for tab dividers. These colors are treated as a circular array.
     * Providing one color will mean that all tabs are indicated with the same color.
     */
    public void setDividerColors(int... colors) {
        mTabStrip.setDividerColors(colors);
    }

    /**
     * Set the {@link ViewPager.OnPageChangeListener}. When using {@link SlidingTabLayout} you are
     * required to set any {@link ViewPager.OnPageChangeListener} through this method. This is so
     * that the layout can update it's scroll position correctly.
     *
     * @see ViewPager#setOnPageChangeListener(ViewPager.OnPageChangeListener)
     */
    public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
        mViewPagerPageChangeListener = listener;
    }

    /**
     * Set the custom layout to be inflated for the tab views.
     *
     * @param layoutResId Layout id to be inflated
     * @param textViewId  id of the {@link TextView} in the inflated view
     */
    public void setCustomTabView(int layoutResId, int textViewId) {
        mTabViewLayoutId = layoutResId;
        mTabViewTextViewId = textViewId;
    }

    /**
     * Sets the associated view pager. Note that the assumption here is that the pager content
     * (number of tabs and tab titles) does not change after this call has been made.
     */
    public void setViewPager(ViewPager viewPager) {
        mTabStrip.removeAllViews();

        mViewPager = viewPager;
        if (viewPager != null) {
            viewPager.setOnPageChangeListener(new InternalViewPagerListener());
            populateTabStrip();
        }
    }

    /**
     * Create a default view to be used for tabs. This is called if a custom tab view is not set via
     * {@link #setCustomTabView(int, int)}.
     */
    protected TextView createDefaultTabView(Context context) {
        TextView textView = new TextView(context);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
        textView.setTypeface(Typeface.DEFAULT_BOLD);

        // 这会移除 Holo 的默认背景强调以及选项卡的粗体文本
        //  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // If we're running on Honeycomb or newer, then we can use the Theme's
        // selectableItemBackground to ensure that the View has a pressed state
        //       TypedValue outValue = new TypedValue();
        //       getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
        //               outValue, true);
        //       textView.setBackgroundResource(outValue.resourceId);
        //   }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            // If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
            textView.setAllCaps(true);
        }

        int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
        textView.setPadding(padding, padding, padding, padding);

        return textView;
    }

    private void populateTabStrip() {
        final PagerAdapter adapter = mViewPager.getAdapter();
        final OnClickListener tabClickListener = new TabClickListener();

        for (int i = 0; i < adapter.getCount(); i++) {
            View tabView = null;
            TextView tabTitleView = null;

            if (mTabViewLayoutId != 0) {
                // If there is a custom tab view layout id set, try and inflate it
                tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip,
                        false);
                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            }

            if (tabView == null) {
                tabView = createDefaultTabView(getContext());
            }

            if (tabTitleView == null && TextView.class.isInstance(tabView)) {
                tabTitleView = (TextView) tabView;
            }

            tabTitleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);

            // =========================== 水平居中 ============================
            LinearLayout.LayoutParams layoutParams= new LinearLayout.LayoutParams(0,
                    LayoutParams.WRAP_CONTENT, 1.0f);
            tabView.setLayoutParams(layoutParams);
            // =============================== 以上 =========

            mTabStrip.addView(tabView);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        if (mViewPager != null) {
            scrollToTab(mViewPager.getCurrentItem(), 0);
        }
    }

    private void scrollToTab(int tabIndex, int positionOffset) {
        final int tabStripChildCount = mTabStrip.getChildCount();
        if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
            return;
        }

        View selectedChild = mTabStrip.getChildAt(tabIndex);
        if (selectedChild != null) {

            // ============ 调用在每次选项改变时更新文本颜色的新方案
            updateSelectedTitle(tabIndex);
            // =============================== 以上 =========

            int targetScrollX = selectedChild.getLeft() + positionOffset;

            if (tabIndex > 0 || positionOffset > 0) {
                // If we're not at the first child and are mid-scroll, make sure we obey the offset
                targetScrollX -= mTitleOffset;
            }

            scrollTo(targetScrollX, 0);
        }
    }

    private class InternalViewPagerListener implements ViewPager.OnPageChangeListener {
        private int mScrollState;

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            int tabStripChildCount = mTabStrip.getChildCount();
            if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
                return;
            }

            mTabStrip.onViewPagerPageChanged(position, positionOffset);

            View selectedTitle = mTabStrip.getChildAt(position);
            int extraOffset = (selectedTitle != null)
                    ? (int) (positionOffset * selectedTitle.getWidth())
                    : 0;
            scrollToTab(position, extraOffset);

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageScrolled(position, positionOffset,
                        positionOffsetPixels);
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            mScrollState = state;

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageScrollStateChanged(state);
            }
        }

        @Override
        public void onPageSelected(int position) {
            if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
                mTabStrip.onViewPagerPageChanged(position, 0f);
                scrollToTab(position, 0);
            }

            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageSelected(position);
            }
        }

    }

    private class TabClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                if (v == mTabStrip.getChildAt(i)) {
                    mViewPager.setCurrentItem(i);
                    return;
                }
            }
        }
    }

}


SlidingTabLayout简单使用 SlidingTabLayout的简单使用 立即下载

相关推荐

HDR标准核心参数全解析:从PQ/HLG到元数据,一篇搞懂技术选型

本文全面解析HDR标准的核心参数,包括PQ/HLG传输函数和元数据机制,帮助读者理解技术选型的关键因素。通过对比主流HDR标准的技术细节,提供从内容创作到硬件适配的实用指南,助力实现更真实的视觉体验。

weixin_31766003的博客 308

94.android 简单的TabLayout(SlidingTabLayout)+ViewPager+fragment的效果

//先上效果图: //第一步 导入依赖: implementation 'com.flyco.tablayout:FlycoTabLayout_Lib:2.0.2@aar' //第二步 我的MainActivity代码实现: public class MainActivity extends AppCompatActivity { priva...

曹二少的博客 3241

汽车标定工具--INCA使用方法

汽车这种各具差异的风格,我们可以把这个脾气称为驾驶性,驾驶性会影响着车辆的定位,是来做商务接待,还是跑货拉拉,或是一眼就是改装车气质,就看车辆的脾气了。这个驾驶性,其实简单点说,就是汽车设置的一些关于动力的参数,让车辆有如此性能的表现。INCA是属于ETAS旗下的一款基础产品,能够与其他试验平台,HIL系统等实现接口交互,具备全面的测试和标定功能,支持CCP或XCP等协议,可对标定数据进行管理,可用于数据采集、标定、ECU闪存编程ProF集成,可用于带图形策略数据显示示波器,界面自编程等功能,实在很强大。

cai2347254的博客 1万+

SlidingTabLayout:完全自定义Tab导航栏UI风格

情景 效果 使用 导入 使用 Demo地址 SlidingTabLayout源码 SlidingTabStrip源码情景系统自带的Tablayout拓展性实在太差,但很多时候又需要对Tab进行类iOS风格的自定义,使用反射TabLayout无果之后选择了更简单的SlidingTabLayout。SlidingTabLayout,看到有说是官方的Component,但是在Api27找了半天没找到,不知

ffengz的博客 1万+

手把手教你用单结晶体管搭建简易振荡电路(含电路图和波形分析)

本文详细介绍了如何使用单结晶体管(UJT)搭建简易振荡电路,包括电路设计、波形分析和实战技巧。通过具体的电路图和参数计算,帮助电子爱好者和工程师快速掌握UJT振荡器的设计与调试方法,适用于脉冲信号生成和时钟源制作等应用场景。

weixin_29207533的博客 526

DAZ STUDIO 快速渲染技巧

DAZ STUDIO 快速渲染技巧: 本文将向您展示几个快速渲染技巧。您将学习如何使您的Daz Iray渲染和照明在Daz工作室内更快。 当你有一个大场景,这可能需要很多小时进行渲染。 但是如果你想大幅度降低渲染时间呢?这篇文章的提示应该能让你达到这个目标。 首先,我们需要弄清楚一件事——没有“完美的环境或设置”这样的东西。是因为渲染设置是高度个性化和主观性的东西,这主要取决于场景和硬件。如果你有一个功能强大的计算机,你可以允许更多的低渲染时间,反之亦然。因此,一切都取决于您尝试渲染的对象和机器。

DAZSTUDIO的博客 9692

安卓开发-SlidingTablayout案例(小白系列)

琢磨了两天,看了各种教程和文章,终于有所领悟,哈哈哈哈,脑子笨我也很无奈 总结下过程: 一、创建布局,&lt;slidingtablayout&gt;和&lt;viewpager&gt; 二、创建要显示在viewpage中的xml文件 三、设置xml对应的fragment类,onCreateView方法中绑定对应的xml文件 四、在Mainactivity中设置,title和要显示的fr...

hhyihquk1的博客 3093

海康视觉通讯配置

本文介绍了海康通讯管理中TCP和Modbus协议的配置方法。TCP通讯时,视觉系统作为服务器接收PLC客户端发送的触发信号,需注意十进制与十六进制字符串的转换。Modbus配置需填写PLC的IP地址和寄存器首地址,并预先定义整型变量。TCP通讯需开启16进制发送模式以避免数据格式问题。文章重点说明了不同通讯方式下的数据格式转换和参数设置要点。

A567852的博客 2277

示例代码中的 SlidingTabLayout 简单使用(一)

示例代码中的 SlidingTabLayout 简单使用(一)

antimage08的博客 4696

UE游戏引擎材质简单入门

什么是物体的材质,材质属性定义了物体的某些特性,从而决定了物体表面是如何与光线相作用的。UE中物理基础渲染(Physically Based Rendering OR PBR)几乎可以让我们模拟显示世界中的任何材质。那么如何在UE中制作出真实的PBR材质,基于我们提供的游戏引擎插件,如何将这些材质资源导出,并应用到 SuperMap iClient3D for Cesium/WebGL 平台上,提升模型的显示效果呢,下面小编将详细讲解一下。

m0_71055362的博客 2522

【AutoCAD中实现双击文本编辑功能】

例如:以下是官方博客例子浅析先加入相关的头文件和库文件。在AutoCAD中有一个很重要的功能,就是双击图形尺寸或文本后会出现一个文本编辑框,用户可在该编辑框中修改文字。本文介绍了如何使用AcEdInplaceTextEditor来实现该功能。实现cad的消息监听。创建一个消息监听的类并在cad中注册来实现消息监听。主要是监听键盘输入。提示:以下是本篇文章正文内容,下面案例可供参考提示:这里对文章进行总结:例如:以上就是今天要讲的内容,本文仅仅简单介绍了的函数和方法。

我的博客 1153

【Android UI】SlidingTabLayout使用小结

1、从https://developer.android.com/intl/zh-cn/samples/SlidingTabsBasic/index.html下载项目 2、将SlidingTabLayout.java 和 SlidingTabStrip拷贝到自己项目中 3、layout在合适的位置添加<LinearLayout android:layout_width="match_p

Blue布洛的专栏 1万+

第14.8章 高翔博士最新开源框架Lightning-LM源码解读(八):位姿平滑器PoseSmoother深度剖析,从原理到代码实现

本文深度解析了高翔博士开源框架Lightning-LM中的位姿平滑器PoseSmoother模块。该模块通过设置平滑因子,在保证位姿准确性的同时减少突变,使位姿变化更平稳。文章详细讲解了模块功能、数据流程和核心代码实现,包括构造函数、拷贝构造函数以及关键的PushDRPose和PushPose函数。重点分析了位姿平滑算法原理,涉及运动有效性校验、位姿队列维护和平滑因子调节等核心机制。此外还介绍了相关C++语法(如显式构造函数、默认拷贝构造)和优化方向。本解析为SLAM学习者提供了位姿平滑处理的实用实现范例。

行知SLAM 621

SlidingTabLayout的使用--替代ActionBar的Tab导航

最近在使用ActionBar的时候,如果使用的是最新版V7包或者最新的SDK平台,就会发现 ActionBar的导航功能已经不建议使用了。主要的原因是ActionBar自带Tab导航自定义性差(只能通过style修改),而且不再建议使用ActionBar。SlidingTabLayout就是ActionBar导航的替代品,使用它可以轻松的实现导航功能。 使用SlidingTabLayou

Mr_WangGang的专栏 1万+

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Android 简单SlidingTabLayout的用法

SlidingTabLayout的用法 1、导入Gradle依赖 implementation 'com.flyco.tablayout:FlycoTabLayout_Lib:2.1.2@aar' 2、布局 布局采用SlidingTabLayout和ViewPage 配合使用,在ViewPage中添加fragment,从而实现左右滑动 具体代码如下: <?xml version="1.0" encoding="utf-8"?> <Linear

小虎的博客 4434

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

android 标题简单实现,SlidingTabLayout

SlidingTabLayout【Android】SlidingTabLayout实现标题栏,教你制作title标题 简单易学。作者:程序员小冰,CSDN博客:http://blog.csdn.net/qq_21376985,QQ986945193 微博:http://weibo.com/mcxiaobing首先先给大家看一下效果图:介绍:本小demo里面引用了两个google的官方类,Slidi...

weixin_39628186的博客 303

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

java showMsg代码_Java SlidingTabLayout.showMsg方法代码示例

import com.flyco.tablayout.SlidingTabLayout; //导入方法依赖的package包/类@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_sliding...

weixin_39736650的博客 245

SlidingTabLayout+ViewPager的使用

在Fragment中拿到传过来的type,随后即可在Fragment中处理代码了。前提,SlidingTabLayout的引用和基本用法参考下面链接。

weixin_48001141的博客 770

Android SlidingTabLayout定制分割线和指示条颜色

 Android SlidingTabLayout定制分割线和指示条颜色 Android SlidingTabLayout默认的滑动指示条是系统默认的某个蓝色系色值,分割线是灰色。如果要自定义实现滑动指示条和分割线定制颜色,则主要通过SlidingTabLayout的setCustomTabColorizer()方法实现。 现在给出一个例子加以说明。 (1)首先做一个MainAct

Zhang Phil 1万+

Android开发Viewpager2和SlidingTabLayout结合使用

【代码】Android开发Viewpager2和SlidingTabLayout结合使用。

聪哥的专栏 362

android sliding tab,android – 刷新SlidingTabLayout

图片中的示例:>清空PagerView>具有新内容的PagerView(SlidingTabLayout不更新)>新的视图实例(SlidingTabLayout已更新);这是我的代码:public class CharSortFragment extends Fragment {private final String TAG = "CharSortFragment";priva...

weixin_35332816的博客 376

Android TabLayout加强版SlidingTabLayout

Android TabLayout加强版SlidingTabLayout 众所周知TabLayout纯在很多问题和不足,因此各路神仙对其各种修改,在GitHub上比较被肯定三个TabLayout其中一个就是 SlidingTabLayout,接下来我简单介绍一下使用: 首先:依赖和XML配置 //FlycoTabLayout //进阶tablayout ...

赵星海 4247

利用Toolbar和SlidingTabLayout实现Tab

利用Toolbar下实现Tab@(Blog)[马克飞象|Markdown|Android]首先你必须清楚Toolbar、ViewPaper的使用,之前选择直接看网上Toolbar下增加Tab的Blog,看起来好像很难的样子,于是乎,便把这几个分开看了,再回来实现这个功能的时候,发现其实很简单。 利用Toolbar替换ActionBar ViewPager 用法实现Tab功能我们需要使用到Goog

XuDaojie的专栏 1万+

android SlidingTabLayout实现ViewPager页卡滑动效果

先来张效果图(可以滑动切换页卡) 主页面布局文件 remind_auction_new_list.xml : <RelativeLayout style="@style/Rosemary.Plane" xmlns:android="http://schemas.android.com/apk/res/android"> <com.liam.r

pengkv的专栏 4306
上一篇: 示例代码中的 SlidingTabLayout 简单使用(一)
下一篇: Snackbar 的简单使用
antimage08
博客等级 码龄11年 17粉丝 59原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值