Android imitates ViewpagerIndicator of Sohu news

Source: Internet
Author: User

Android imitates ViewpagerIndicator of Sohu news

I haven't written a blog for a long time. Today, I have nothing to worry about.

For example, we will imitate the title of Sohu news today, first.

 

 

1. Next, let's analyze this effect.

The following content should be viewpager. We can use a LinearLayout + HorizontalScrollView on the tab of the header. If the rolling effect is displayed, we can use the scrollTo we learned to clarify the general idea, let's start code!

2. Customize LinearLayout

We can see that the red rectangle should be in line with the overall LinearLayout, so we can customize the LinearLayout to draw the rectangle. Scroll is to change the position of the rectangle.

 

Public class ViewpagerIndicator extends LinearLayout {/*** Paint brush, bottom rectangle */private paint Paint;/*** Number of child views */private int mCount; private int mTop; private int mWidth; private int mLeft; private int mHeight = 5; public OnTextClick onTextClick; public ViewpagerIndicator (Context context) {super (context);} public ViewpagerIndicator (Context context, AttributeSet attrs) {super (context, attrs); setBackgroundColor (Color. TRANSPARENT); paint = new Paint (); paint. setColor (getResources (). getColor (R. color. red); paint. setAntiAlias (true);} public interface OnTextClick {public void textViewClick (int position);} public void setOnTextClick (OnTextClick onTextClick) {this. onTextClick = onTextClick;} @ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super. onMeasure (widthMeasureSpec, heightMeasureSpec); // overall height mTop = getMeasuredHeight (); // overall width int width = getMeasuredWidth (); // Add the indicator height int height = mTop + mHeight; // indicator width mWidth = width/mCount; setMeasuredDimension (width, height );}

In onMeasure, we get the desired value about the location distance. Next we can draw the desired rectangle in onDraw.

 

 

/*** Draw indicator * @ param canvas */protected void onDraw (Canvas canvas) {Rect rect = new Rect (mLeft, mTop, mLeft + mWidth, mTop + mHeight ); canvas. drawRect (rect, paint );}

 

That's right, it's just two sentences of code. After that, you can follow the scrolling effect by constantly changing left.

 

/*** Scroll effect ** @ param position * @ param positionOffset */public void scrollTo (int position, float positionOffset) {mLeft = (int) (position + positionOffset) * mWidth); postInvalidate ();}
The two parameters in the method can be obtained through the callback method onPageScrolled of viewpager. position is the current tab, and positionOffset is equivalent to the sliding percentage of 0.0 ~ Between 0.0.

 

3. Use Custom Controls

OK. The general idea has been clarified. Next we can use our own Indicator.

 

     
          
               
                
                 
       
        
         
          
           
            
             
              
               
                
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
       
      
 
First, do not be scared by the text view that appears mostly like a dog. In fact, it is only possible to paste and copy a text file, we can also use TextView t = new TextView () in our own LinearLayout, and then add it in. Both methods are acceptable.

 

However, we obviously do not want to get the id for so many textviews and then get its instance and then setOnClick, so we can directly set it in the Custom ViewGroup.

 

@ Override protected void onFinishInflate () {super. onFinishInflate (); mCount = getChildCount ();/*** listen to click events, callback interface */for (int I = 0; I
 
Through the callback interface, we can easily find the tab that is clicked. Next let's take a look at the usage method.

 

 

public class MainActivity extends Activity implements ViewPager.OnPageChangeListener,ViewpagerIndicator.OnTextClick{    private ViewPager viewPager;    private int lastX = 0;    private ViewpagerIndicator indicator;    private HorizontalScrollView horizontalScrollView;    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initViews();    }    private void initViews() {        viewPager = (ViewPager) findViewById(R.id.viewpager);        indicator = (ViewpagerIndicator) findViewById(R.id.indicator);        indicator.setOnTextClick(this);        horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizon);        viewPager.setAdapter(new MyAdapter());        viewPager.setOnPageChangeListener(this);    }
Some necessary instantiation.

 

 

/*** The overall indicator does not scroll independently only when the second item is rolled from the first item or the second item is rolled from the second item, the rest are full layout scrolling * @ param position * @ param positionOffset * @ param positionOffsetPixels */public void onPageScrolled (int position, float positionOffset, int positionOffsetPixels) {if (! (Position = 0 & positionOffset-lastX> = 0) |! (Position = 1 & positionOffset-lastX <= 0) {horizontalScrollView. scrollTo (int) (positionOffset + position-1) * indicator. getIndicatorWidth (), 0);} indicator. scrollTo (position, positionOffset); lastX = (int) positionOffset;} @ Override public void onPageSelected (int position) {indicator. resetTextViewColor (); indicator. setFocusTextView (position) ;}@ Override public void onPageScrollStateChanged (int state ){}
By observing the Sohu news, we can see that when we slide from the first page to the second page, only the Indicator is rolling, and then the whole is rolling, so we need to make a good judgment, the indicator stays on the second tab displayed during the overall rolling process. Let's take a look at the actual results.

 



The effect is still wide.

 

Project source code

 

Related Article

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.