Skip to content Skip to sidebar Skip to footer

How Can I Develop The Pagerslidingtabstrip With Images In Android?

I am using the PagerSlidingTabStrip in myapp .In this titles are setting fine but images are not setting tabstrip .I searched alot in google but didn't get the correct result.But t

Solution 1:

I was also interested doing same as yours, Finally I did it for you.

Import 'SlidingTabsBasic' demo from android-sdk sample or download it from google android samples from Here.

1.create custom_tab.xml with only a TextView 2.In 'SlidingTabsBasicFragment.class' do below changes:

-add this code in onViewCreated()

mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
mSlidingTabLayout.setCustomTabView(R.layout.custom_tab, 0);
mSlidingTabLayout.setViewPager(mViewPager);

-in SamplePagerAdapter class, replace this function code

public CharSequence getPageTitle(int position)
{
    //return "Item " + (position + 1);Drawableimage= getActivity().getResources().getDrawable(imageResId[position]);
    image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
    SpannableStringsb=newSpannableString(" ");
    ImageSpanimageSpan=newImageSpan(image, ImageSpan.ALIGN_BOTTOM);
    sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return sb;
}

If you have done it properly, You will get something like this:

Tab Strip

Hope this will help!

Solution 2:

Well it wasn't hard looking at the code of SlidingTabLayout I have commented few lines of code. The code is self explanatory i guess.

Well you can customize it according to your needs.

import android.content.Context;
import android.graphics.Typeface;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

    publicinterfaceTabColorizer {

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

    }

    privatestaticfinalintTITLE_OFFSET_DIPS=24;
    privatestaticfinalintTAB_VIEW_PADDING_DIPS=16;
    privatestaticfinalintTAB_VIEW_TEXT_SIZE_SP=12;

    privateint mTitleOffset;

    privateint mTabViewLayoutId;
    privateint mTabViewTextViewId;
    privateboolean mDistributeEvenly;

    private ViewPager mViewPager;
    private SparseArray<String> mContentDescriptions = newSparseArray<String>();
    private ViewPager.OnPageChangeListener mViewPagerPageChangeListener;

    privatefinal SlidingTabStrip mTabStrip;
    int prepage;
    int currpage;

    publicSlidingTabLayout(Context context) {
        this(context, null);
    }

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

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

        // 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 = newSlidingTabStrip(context);
        addView(mTabStrip, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    }

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

    publicvoidsetDistributeEvenly(boolean distributeEvenly) {
        mDistributeEvenly = distributeEvenly;
    }

    /**
     * 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.
     */publicvoidsetSelectedIndicatorColors(int... colors) {
        mTabStrip.setSelectedIndicatorColors(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)
     */publicvoidsetOnPageChangeListener(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
     */publicvoidsetCustomTabView(int layoutResId) {
        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.
     */publicvoidsetViewPager(ViewPager viewPager) {
        mTabStrip.removeAllViews();

        mViewPager = viewPager;
        if (viewPager != null) {
            viewPager.setOnPageChangeListener(newInternalViewPagerListener());
            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) {
        TextViewtextView=newTextView(context);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        textView.setLayoutParams(newLinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        TypedValueoutValue=newTypedValue();
        getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
                outValue, true);
        textView.setBackgroundResource(outValue.resourceId);
        textView.setAllCaps(true);

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

        return textView;
    }

    privatevoidpopulateTabStrip() {
        finalPagerAdapteradapter= mViewPager.getAdapter();
        final View.OnClickListenertabClickListener=newTabClickListener();

        for (inti=0; i < adapter.getCount(); i++) {
            ViewtabView=null;
            TextViewtabTitleView=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);
                ImageViewiv= (ImageView) tabView.findViewById(R.id.imageView1);
//                tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);//           }////            if (tabView == null) {//                tabView = createDefaultTabView(getContext());//            }////            if (tabTitleView == null && TextView.class.isInstance(tabView)) {//                tabTitleView = (TextView) tabView;//            }if (mDistributeEvenly) {
                LinearLayout.LayoutParamslp= (LinearLayout.LayoutParams) tabView.getLayoutParams();
                lp.width = 0;
                lp.weight = 1;
            }
            iv.setImageResource(R.drawable.ic_launcher);
//            tabT itleView.setText(adapter.getPageTitle(i));
            tabView.setOnClickListener(tabClickListener);
            Stringdesc= mContentDescriptions.get(i, null);
            if (desc != null) {
                tabView.setContentDescription(desc);
            }

            mTabStrip.addView(tabView);
            if (i == mViewPager.getCurrentItem()) {
                tabView.setSelected(true);
            }
        }
    }

    publicvoidsetContentDescription(int i, String desc) {
        mContentDescriptions.put(i, desc);
    }

    @OverrideprotectedvoidonAttachedToWindow() {
        super.onAttachedToWindow();

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

    privatevoidscrollToTab(int tabIndex, int positionOffset) {
        finalinttabStripChildCount= mTabStrip.getChildCount();
        if (tabStripChildCount == 0 || tabIndex < 0 || tabIndex >= tabStripChildCount) {
            return;
        }

        ViewselectedChild= mTabStrip.getChildAt(tabIndex);
        if (selectedChild != null) {
            inttargetScrollX= 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);
        }
    }

    privateclassInternalViewPagerListenerimplementsViewPager.OnPageChangeListener {
        privateint mScrollState;

        @OverridepublicvoidonPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            inttabStripChildCount= mTabStrip.getChildCount();
            if ((tabStripChildCount == 0) || (position < 0) || (position >= tabStripChildCount)) {
                return;
            }

            mTabStrip.onViewPagerPageChanged(position, positionOffset);

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

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

        @OverridepublicvoidonPageScrollStateChanged(int state) {
            mScrollState = state;

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

        @OverridepublicvoidonPageSelected(int position) {
          //  TextView tab = (TextView) mTabStrip.getChildAt(position);// tab.setTextColor(Color.BLACK);if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
                mTabStrip.onViewPagerPageChanged(position, 0f);
                scrollToTab(position, 0);
            }
            for (inti=0; i < mTabStrip.getChildCount(); i++) {
                mTabStrip.getChildAt(i).setSelected(position == i);
            }
            if (mViewPagerPageChangeListener != null) {
                mViewPagerPageChangeListener.onPageSelected(position);
            }
        }

    }

    privateclassTabClickListenerimplementsView.OnClickListener {
        @OverridepublicvoidonClick(View v) {
            for (inti=0; i < mTabStrip.getChildCount(); i++) {
                if (v == mTabStrip.getChildAt(i)) {
                    mViewPager.setCurrentItem(i);
                    return;
                }
            }
        }
    }

}

SlidingTabStrip.java

import android.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;

classSlidingTabStripextendsLinearLayout {

    privatestaticfinalintDEFAULT_BOTTOM_BORDER_THICKNESS_DIPS=0;
    privatestaticfinalbyteDEFAULT_BOTTOM_BORDER_COLOR_ALPHA=0x26;
    privatestaticfinalintSELECTED_INDICATOR_THICKNESS_DIPS=3;
    privatestaticfinalintDEFAULT_SELECTED_INDICATOR_COLOR=0xFF33B5E5;

    privatefinalint mBottomBorderThickness;
    privatefinal Paint mBottomBorderPaint;

    privatefinalint mSelectedIndicatorThickness;
    privatefinal Paint mSelectedIndicatorPaint;

    privatefinalint mDefaultBottomBorderColor;

    privateint mSelectedPosition;
    privatefloat mSelectionOffset;

    private SlidingTabLayout.TabColorizer mCustomTabColorizer;
    privatefinal SimpleTabColorizer mDefaultTabColorizer;

    SlidingTabStrip(Context context) {
        this(context, null);
    }

    SlidingTabStrip(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);

        finalfloatdensity= getResources().getDisplayMetrics().density;

        TypedValueoutValue=newTypedValue();
        context.getTheme().resolveAttribute(R.attr.colorForeground, outValue, true);
        finalintthemeForegroundColor=  outValue.data;

        mDefaultBottomBorderColor = Color.YELLOW;
        //setColorAlpha(themeForegroundColor,// DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);

        mDefaultTabColorizer = newSimpleTabColorizer();
        mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);

        mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
        mBottomBorderPaint = newPaint();
        mBottomBorderPaint.setColor(mDefaultBottomBorderColor);

        mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
        mSelectedIndicatorPaint = newPaint();
    }

    voidsetCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
        mCustomTabColorizer = customTabColorizer;
        invalidate();
    }

    voidsetSelectedIndicatorColors(int... colors) {
        // Make sure that the custom colorizer is removed
        mCustomTabColorizer = null;
        mDefaultTabColorizer.setIndicatorColors(colors);
        invalidate();
    }

    voidonViewPagerPageChanged(int position, float positionOffset) {
        mSelectedPosition = position;
        mSelectionOffset = positionOffset;
        invalidate();
    }

    @OverrideprotectedvoidonDraw(Canvas canvas) {
        finalintheight= getHeight();
        finalintchildCount= getChildCount();
        final SlidingTabLayout.TabColorizertabColorizer= mCustomTabColorizer != null
                ? mCustomTabColorizer
                : mDefaultTabColorizer;

        // Thick colored underline below the current selectionif (childCount > 0) {
            ViewselectedTitle= getChildAt(mSelectedPosition);
            intleft= selectedTitle.getLeft();
            intright= selectedTitle.getRight();
            intcolor= tabColorizer.getIndicatorColor(mSelectedPosition);

            if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
                intnextColor= tabColorizer.getIndicatorColor(mSelectedPosition + 1);
                if (color != nextColor) {
                    color = blendColors(nextColor, color, mSelectionOffset);
                }

                // Draw the selection partway between the tabsViewnextTitle= getChildAt(mSelectedPosition + 1);
                left = (int) (mSelectionOffset * nextTitle.getLeft() +
                        (1.0f - mSelectionOffset) * left);
                right = (int) (mSelectionOffset * nextTitle.getRight() +
                        (1.0f - mSelectionOffset) * right);
            }


            canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
                    height, mSelectedIndicatorPaint);
        }

        // Thin underline along the entire bottom edge
        canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
    }

    /**
     * Set the alpha value of the {@code color} to be the given {@code alpha} value.
     */privatestaticintsetColorAlpha(int color, byte alpha) {
        return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
    }

    /**
     * Blend {@code color1} and {@code color2} using the given ratio.
     *
     * @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
     *              0.0 will return {@code color2}.
     */privatestaticintblendColors(int color1, int color2, float ratio) {
        finalfloatinverseRation=1f - ratio;
        floatr= (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
        floatg= (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
        floatb= (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
        return Color.rgb((int) r, (int) g, (int) b);
    }

    privatestaticclassSimpleTabColorizerimplementsSlidingTabLayout.TabColorizer {
        privateint[] mIndicatorColors;



        @OverridepublicintgetIndicatorColor(int position) {
            return mIndicatorColors[position % mIndicatorColors.length];
        }

        voidsetIndicatorColors(int... colors) {
            mIndicatorColors = colors;
        }
    }
}

activity_main.xml

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.customslidingtablayout.MainActivity" ><com.example.customslidingtablayout.SlidingTabLayoutandroid:layout_alignParentTop="true"android:id="@+id/sliding_tabs"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@color/red" /><android.support.v4.view.ViewPagerandroid:layout_below="@id/sliding_tabs"android:id="@+id/viewpager"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@android:color/white" /></RelativeLayout>

tab_indicator.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><ImageViewandroid:id="@+id/imageView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerHorizontal="true"android:layout_centerVertical="true"android:src="@drawable/abc_btn_switch_to_on_mtrl_00012" /></RelativeLayout>

In Activity

ViewPager mViewPager;
FragmentAdapter mAdapter;
SlidingTabLayout mSlidingTabLayout;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

     mViewPager = (ViewPager) findViewById(R.id.viewpager);
     mAdapter = newFragmentAdapter(getFragmentManager());
     mViewPager.setAdapter(mAdapter);

     mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);

     mSlidingTabLayout.setCustomTabView(R.layout.tab_indicator);
     mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.black));
     mSlidingTabLayout.setDistributeEvenly(true);
     mSlidingTabLayout.setViewPager(mViewPager);

}

enter image description here

Solution 3:

I ever writed a project about this topic. Here is my project, take a look, maybe you will be inspired.

Post a Comment for "How Can I Develop The Pagerslidingtabstrip With Images In Android?"