Switch TabIndicator and tabtabindicator Based on Weibo Tab

Source: Internet
Author: User

Switch TabIndicator and tabtabindicator Based on Weibo Tab

First read one:

At that time, when I received this requirement for the first time, I first thought of rewriting LinearLayout and then listening to the rolling layout of click events of ViewPager and Tab. But after writing it, I encountered a problem, that is, the top Tab can only scroll with the click event or ViewPager.

The source code of TabLayout is analyzed,

TabLayout inherits from HorizontalScrollView. If the UI requirements are not strict, basic functions can be implemented. However, the bad thing is that the width of the indicator (line under the text) does not provide a modification method, and the indicator displacement animation cannot be customized.

Inspired by TabLayout, a custom MyTabIndicator inherits from HorizontalScrollVIew.

The basic structure of the Code:

MyTabIndicator. java:

[Html]View plaincopy

PublicclassMyTabIndicatorextendsHorizontalScrollView {

PrivateclassTabLayoutextendsLinearLayout {}

}

The child view TabLayout is nested in MyTabIndicator.

Supported custom attributes:

The above xml mainly serves to customize attributes, the normal mode and size of text, the selected color and size, the background color, the indicator color, and the indicator width (the maximum indicator width is the Tab width)

The following describes several key methods:

1. MyTabIndicator Constructor

Public MyTabIndicator (Context context) {this (context, null);} public MyTabIndicator (Context context, AttributeSet attrs) {this (context, attrs, 0 );} public MyTabIndicator (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); // read if (attrs! = Null) {TypedArray typedArray = context. obtainStyledAttributes (attrs, R. styleable.MyTabIndicator); TEXTNORMALCOLOR = typedArray. getColor (R. styleable.MyTabIndicator_textNormalColor, 0x80FFFFFF); TEXTSELECTEDCOLOR = typedArray. getColor (R. styleable.MyTabIndicator_textSelectedColor, 0 xFFFFFFFF); TEXTNORMALSIZE = typedArray. getDimension (R. styleable.MyTabIndicator_textNormalSize, 13); TEXTSELECTEDSIZE = typedArray. getDimension (R. styleable.MyTabIndicator_textSelectedSize, 15); BACKGROUNDCOLOR = typedArray. getColor (R. styleable.MyTabIndicator_backGroundColor, 0xFF242425); INDICATORCOLOR = typedArray. getColor (R. styleable.MyTabIndicator_indicatorColor, 0 xFFFFFFFF); INDICATORWIDTH = typedArray. getDimension (R. styleable.MyTabIndicator_indicatorWidth, 0); typedArray. recycle ();} else {TEXTNORMALCOLOR = Color. parseColor ("#80 FFFFFF"); TEXTSELECTEDCOLOR = Color. parseColor ("# FFFFFF"); TEXTNORMALSIZE = 13; TEXTSELECTEDSIZE = 15; BACKGROUNDCOLOR = Color. parseColor ("#242425"); INDICATORCOLOR = Color. parseColor ("# FFFFFF"); INDICATORWIDTH = 0;} // hide the scroll bar setHorizontalScrollBarEnabled (false); // Add the tab container mTabLayout = new TabLayout (context ); layoutParams params = new LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); MTabLayout. setLayoutParams (params); addView (mTabLayout); // initialize the title width mTitleWidth = getScreenWidth ()/mTabVisibleCount ;}
It is mainly used to initialize some custom attributes. If you use the attributes in common_attr.xml in the layout xml file, the attributes you enter will be used. If you do not enter a property, the default property is used.

Then add the Tab container TabLayout to TabIndicator. here you need to set the LayoutParams of mTabLayout. The width and height are both matchparent.

Next, initialize the width of the Tab title, and getScreenWidth () is the width of the screen.
2. TabLayout Constructor

public TabLayout(Context context) {    this(context, null);}public TabLayout(Context context, AttributeSet attrs) {    this(context, attrs, 0);}public TabLayout(Context context, AttributeSet attrs, int defStyleAttr) {    super(context, attrs, defStyleAttr);    setOrientation(HORIZONTAL);    setBackgroundColor(BACKGROUNDCOLOR);    mPaintIndicator = new Paint();    mPaintIndicator.setColor(INDICATORCOLOR);    mPaintIndicator.setStyle(Paint.Style.FILL);    mPaintIndicator.setStrokeWidth(Local.dip2px(2));}

It is mainly used to initialize the layout direction and background color of TabLayout (if there is a problem here, if the background color is not set, the onDraw method cannot be executed, and the reader can use Baidu on his own ).

The next step is to initialize the indicator paint brush. The setStrokeWidth () method is to set the height of the indicator.

3. The onDraw method of TabLayout:

@ Overrideprotected void onDraw (Canvas canvas) {super. onDraw (canvas); // draw the indicator canvas. save (); float x1 = mInitTranslationX + mTranslationX; float x2 = x1 + mIndicatorWidth; float y1, y2; y1 = y2 = getHeight ()-9; canvas. drawLine (x1, y1, x2, y2, mPaintIndicator); canvas. restore ();}

Draw the indicator here. You can also modify this code to draw the indicator style you want. Here I draw line.

In this method, mInitTranslationx is the offset of the indicator to align the indicator with the text in the center.

MTranslationx is the offset of the indicator when it slides. It is used to control the displacement of the indicator from the left of the parent layout.

Adding two variables controls the x coordinate value on the left of the indicator.

Y1, y2, which is the Y coordinate value of the indicator.

(For the usage of Cavas, please Baidu)

4. setTitles: set the number and title of tabs.

 

/*** Fill in the title*@ ParamDatas*/Public void setTitles (List
 
  
Datas) {this. mTabTitles = datas; // if the input list has a value, remove the view if (datas! = Null & datas. size ()> 0) {mTabLayout. removeAllViews (); this. mTabTitles = datas; mTabVisibleCount = Math. min (datas. size (),
  COUNT_DEFAULT_MAX_TAB); MTitleWidth = getScreenWidth ()/mTabVisibleCount; mIndicatorWidth = (int) (mTitleWidth *
  RADIO_TRIANGEL); If (INDICATORWIDTH> 0) {mIndicatorWidth = Math. min (mTitleWidth, (int) INDICATORWIDTH);} // The initial offset mInitTranslationX = (int) (mTitleWidth-mIndicatorWidth)/2.0); for (String title: mTabTitles) {// Add view mTabLayout. addView (getTitleView (title);} // sets the item's click Event setTitleItemClickEvent (); highLightTextView (0 );}}
 

This method is critical. Only when this method is set can tab and title display be available. Calculate the tab width, the initial offset of the indicator, and the Click Event of the title.

5. Title Click Event

/*** Title Click Event*/Private void setTitleItemClickEvent () {int cCount = mTabLayout. getChildCount (); for (int I = 0; I <cCount; I ++) {final int j = I; View view = mTabLayout. getChildAt (I); view. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {if (! IsClick) {isClick = true; if (mViewPager = null) {Message msg = handler. obtainMessage (); mTranslationX ++; msg. what = 3; msg. arg1 = j; handler. sendMessage (msg); resetTextViewColor (); highLightTextView (j);} else {mViewPager. setCurrentItem (j, false) ;}} else {if (! Handler. hasMessages (3) {isClick = false ;}}}});}}

Click the event to determine whether there is a ViewPager. If you do not need to interact with ViewPager, the animation effect is retained by default. If you want to click an event to interact with other actions, you can write a callback interface in this method to meet your needs.

6. slide of the indicator

Int speed =-1;/*** Rollback speed*/Public int SCROLL_SPEED =-10; private Handler handler = new Handler () {@ Override public void handleMessage (final Message msg) {switch (msg. what) {case 3: if (! IsClick) break; final int position = msg. arg1; float a = getWidth ()/mTabVisibleCount * position-mTranslationX; if (speed =-1) {speed = (int) (a/mIndicatorWidth * 2 ); speed = Math. abs (speed); if (speed <20) {speed = 20 ;}} if (a> 0) {SCROLL_SPEED = speed;} else if (a <0) {SCROLL_SPEED =-speed;} mTranslationX + = SCROLL_SPEED; if (a>-speed & a <speed) {mTranslationX = getWidth ()/mTabVisibleCount * position; isClick = false; speed =-1;} else {Message msg1 = handler. obtainMessage (); msg1.what = 3; msg1.arg1 = position; handler. sendMessage (msg1);} Log. I ("mTranslationX", "" + mTranslationX); mTabLayout. invalidate (); break ;}}};

The role of hanlder is constantly achieved by transmitting messages and re-drawing the interface.

Speed is used to determine the speed. If you click tab, handler will determine a rolling speed when the first message is delivered by handler.

IsClick is used to block click events. If the indicator is rolling, isClick is true.

7. Scrolling monitoring of ViewPager and external callback Interface

/*** Callback interface of ViewPager*/Public interface PageChangeListener {void onPageScrolled (int position, float positionOffset, int positionOffsetPixels); void onPageSelected (int position); void onPageScrollStateChanged (int state );} // The callback interface of the external ViewPager is private PageChangeListener onPageChangeListener; // the setting of the callback interface of the external ViewPager is public void setOnPageChangeListener (PageChangeListener pageChangeListener) {this. onPageChangeListener = pageCha NgeListener;} // sets the associated ViewPagerpublic void setViewPager (ViewPager mViewPager, int pos) {this. mViewPager = mViewPager; mViewPager. addOnPageChangeListener (new ViewPager. onPageChangeListener () {@ Override public void onPageSelected (int position) {// set the font color to highlight resetTextViewColor (); highLightTextView (position); // callback if (onPageChangeListener! = Null) {onPageChangeListener. onPageSelected (position) ;}@override public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {// rolling scroll (position, positionOffset); // callback if (onPageChangeListener! = Null) {onPageChangeListener. onPageScrolled (position, positionOffset, positionOffsetPixels) ;}@override public void onPageScrollStateChanged (int state) {// callback if (onPageChangeListener! = Null) {onPageChangeListener. onPageScrollStateChanged (state) ;}}); // set mViewPager. setCurrentItem (pos) on the current page; // highlight highLightTextView (pos );}
8. The scroll Control Method of the indicator when ViewPager is not empty:

 

/*** The indicator follows the finger to scroll and the container to scroll.**@ ParamPosition *@ ParamOffset */Public void scroll (final int position, float offset) {if (offset! = 0.0) {isClick = false;} int tabWidth = getScreenWidth ()/mTabVisibleCount; int last = 1; // container scroll. when moving to the last to last, start to scroll if (offset> 0 & position> = (mTabVisibleCount-last) & mTabLayout. getChildCount ()> mTabVisibleCount) {if (mTabVisibleCount! = 1) {scrollTo (position-(mTabVisibleCount-last) * tabWidth + (int) (tabWidth * offset), 0 );} special processing scrollTo (position * tabWidth + (int) (tabWidth * offset), 0) When else {// is set to count to 1 );}} else if (position <(mTabVisibleCount-last) {scrollTo (0, 0);} if (! IsClick) {// continuously change the offset, invalidate mTranslationX = getWidth ()/mTabVisibleCount * (position + offset); mTabLayout. invalidate ();} else {Message msg = handler. obtainMessage (); mTranslationX ++; msg. what = 3; msg. arg1 = position; handler. sendMessage (msg );}}

Usage:

[Html]View plaincopy

Android: id = "@ + id/myTabIndicator"

Android: layout_width = "match_parent"

Android: layout_height = "44dp"

App: textNormalColor = "#80 FFFFFF"

App: textSelectedColor = "# FFFFFF"

MyTabIndicator. setTitles (mDatas); mViewPager. setAdapter (mAdapter); // set the associated ViewPagermyTabIndicator. setViewPager (mViewPager, 0 );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.