Example code for tablayout custom selection background slider in Android _android

Source: Internet
Author: User
Tags static class

Tablayout is a control in the Android material design package that can produce an interactive effect with the Viewpager in the V4 package. Here I have customized a slider that can follow the tablayout to make a sliding selection of sliderlayout. The effect is shown in the following figure (white box):

The following is the source code of Sliderlayout:

Import Android.content.Context;
Import Android.content.res.TypedArray;
Import android.graphics.drawable.Drawable;
Import Android.support.design.widget.TabLayout;
Import Android.util.AttributeSet;
Import android.view.Gravity;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.ImageView;
Import Android.widget.LinearLayout;
Import java.lang.ref.WeakReference;
/** * Created by Yyw on 2016/4/28. * A slider to display the current index */public class Sliderlayout extends LinearLayout {private int totalnum = 0; Private ImageView mslide
R
Private drawable Msliderimage;
Private weakreference<tablayout> Mtablayoutref; Public Sliderlayout {This (context, null);} public sliderlayout (context, AttributeSet attrs) {T
His (context, attrs, 0);
Public Sliderlayout (context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr);
TypedArray array = context.obtainstyledattributes (Attrs, r.styleable.sliderlayout); Msliderimage = array.Getdrawable (R.styleable.sliderlayout_slider_pic);
if (msliderimage = = null) {msliderimage = Context.getresources (). getdrawable (R.drawable.slider);} array.recycle ();
Init (context); private void init (context context) {Mslider = new ImageView (context); mslider.setimagedrawable (msliderimage); AddView (
Mslider, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); @Override protected void onsizechanged (int w, int h, int oldw, int oldh) {super.onsizechanged (W, H, OLDW, OLDH); resets
Lider (); /** * Reset slider/private void Resetslider () {if (getorientation () = = Horizontal) {Resethorizontalslider ();}/** * Reset
Horizontal slider size */private void Resethorizontalslider () {if (mtablayoutref = null) return;
Tablayout tablayout = Mtablayoutref.get ();
if (tablayout = null) return;
LinearLayout Mtabstrip = (linearlayout) tablayout.getchildat (0);
Totalnum = Mtabstrip.getchildcount (); if (Totalnum > 0) {View Firstview = mtabstrip.getchildat (0); int width = Firstview.getmeasurEdwidth ();
Resetslider (width); }//Reset the size of the slider private void resetslider (int width) {layoutparams params = (layoutparams) mslider.getlayoutparams (); para
Ms.width = width;//Resize the slider params.height = GetHeight ()/2;
params.gravity = gravity.center_vertical;
Mslider.setpadding (WIDTH/10, 0, WIDTH/10, 0);/Set view's left and right inward contraction mslider.setlayoutparams (params);
public void Setupwithtablayout (Tablayout tablayout) {mtablayoutref = new weakreference<> (tablayout);
Resethorizontalslider ();
public static final String TAG = SliderLayout.class.getName (); public static class Slideronpagechangelistener extends Tablayout.tablayoutonpagechangelistener {private final
Weakreference<sliderlayout> Msliderlayoutref; Public Slideronpagechangelistener (Tablayout tablayout, sliderlayout layout) {super (tablayout); msliderlayoutref = new
weakreference<sliderlayout> (layout);
Layout.setupwithtablayout (tablayout); @Override public void onpagescrollstatechanged (int state) {Super.onpagescrollstAtechanged (state); @Override public void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {Super.onpagescroll
Ed (position, Positionoffset, positionoffsetpixels);
Final Sliderlayout layout = Msliderlayoutref.get ();
if (layout!= null) {layout.setscrollposition (position, positionoffset);}} /** * Slide the slider to the specified position * * @param position Current position * @param positionoffset slide to the next or previous position ratio */private void setscrollposition (int Position, float Positionoffset) {final int roundedposition = Math.Round (position + positionoffset); if (Roundedposition & Lt 0 | |
Roundedposition >= totalnum) {return;} float scrollx = Calculatescrollxfortab (position, positionoffset);
Scrollto ((int) scrollx, 0); /** * Calculates the distance the slider needs to slide * * @param position the current selected position * @param positionoffset sliding position of the hundred * @return sliding distance * * Private int calculates Crollxfortab (int position, float positionoffset) {tablayout tablayout = Mtablayoutref.get (); if (tablayout = null) retur
n 0; LinearLayout Mtabstrip = (linearlayout) Tablayout.getchildat (0);
if (Mtabstrip = null) return 0;
The currently selected View Final view Selectedchild = Mtabstrip.getchildat (position); Next View Final View Nextchild = position + 1 < Mtabstrip.getchildcount ()?
Mtabstrip.getchildat (position + 1): null; The width of the currently selected view is final int selectedwidth = Selectedchild!= null?
Selectedchild.getwidth (): 0; The width of the next view final int nextwidth = Nextchild!= null?
Nextchild.getwidth (): 0; The left position of the currently selected view, and the view's azimuth final int left = Selectedchild!= null?
Selectedchild.getleft (): 0;
Calculates the distance that the slider needs to be slid, left +, right-; int scrollx =-((selectedwidth + nextwidth) * Positionoffset * 0.5f)); if (tablayout.gettabmode () = = tablayout.mode_scrollable) {//when sliding mode tablayout will have horizontal sliding scrollx =
TABLAYOUT.GETSCROLLX ()//calculate the sliding distance of the slider relative to Scrollx when the tablayout is sliding; }
}

One of the more critical classes is the Slideronpagechangelistener This class inherits the class of Tablayout.tablayoutonpagechangelistener class we look at the source code (below) which is an interface for listening to Viewpager sliding selection. All we have to do is expand on this class so that sliderlayout can also hear the Viewpager sliding.

public static class Tablayoutonpagechangelistener implements Viewpager.onpagechangelistener {
private final Weakreference<tablayout> Mtablayoutref;
private int mpreviousscrollstate;
private int mscrollstate;
Public Tablayoutonpagechangelistener (Tablayout tablayout) {
mtablayoutref = new Weakreference<> (TabLayout) ;
}
@Override public
void onpagescrollstatechanged (int state) {
mpreviousscrollstate = mscrollstate;
Mscrollstate = State;
}
@Override public
void onpagescrolled (int position, float positionoffset,
int positionoffsetpixels) {
/ /Omit
}
}
@Override public
void onpageselected (int position) {
//omit
}
private void Reset () {
mpreviousscrollstate = Mscrollstate = Scroll_state_idle;
}
}

The method for calculating the distance required for each sliderlayout to slide is calculatescrollxfortab (int position, float positionoffset) (See the source code) according to the monitoring of the viewpager sliding to carry out the relevant calculation and sliding sliderlayout

The use of the time must pay attention to Viewpager.setonpagechangelistener (new Sliderlayout.slideronpagechangelistener (mtablayout,layout)); To be called after Mtablayout.setupwithviewpager (Viewpager);

public class Mainactivity extends appcompatactivity {public static final String TAG = MainActivity.class.getName (); @Ove Rride protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
Final Tablayout mtablayout = (tablayout) Findviewbyid (r.id.tab_layout);
Viewpager Viewpager = (viewpager) Findviewbyid (R.ID.VP);
Sliderlayout layout = (sliderlayout) Findviewbyid (r.id.slider_layout);
Viewpager.setadapter (New Mviewpageradapter (Getsupportfragmentmanager ()));
Mtablayout.setupwithviewpager (Viewpager); Method must be after Mtablayout.setupwithviewpager (Viewpager) or no effect Viewpager.setonpagechangelistener (new
Sliderlayout.slideronpagechangelistener (mtablayout,layout)); Class Mviewpageradapter extends Fragmentpageradapter {public final string[] names = new string[]{"Music", "movie", "TV", "Comprehensive arts", "straight
Broadcasting "," "Music", "movie", "TV", "Comprehensive Arts", "Live"}; Public Mviewpageradapter (fragmentmanager FM) {super (FM);} @Override public Fragment getitem (int position) {return BlAnkfragment.newinstance ("param1", "param2"); @Override public int GetCount () {return} @Override public charsequence getpagetitle (int position) {return names[p
Osition]; }
}
}

Layout:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout 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= "match_parent" android:orientation= "vertical" > <framelayout android:layout_width= "match_parent" android:background= "@color/cardview_dark_background" android:layout_height= "50DP" > <
Com.example.yyw.waterripple.SliderLayout android:id= "@+id/slider_layout" android:layout_width= "Match_parent" android:layout_height= "50DP" app:slider_pic= "@drawable/slider" android:orientation= "Horizontal"/> < Android.support.design.widget.TabLayout android:id= "@+id/tab_layout" android:layout_width= "Match_parent" Android: layout_height= "50DP" app:tabgravity= "center" app:tabmode= "scrollable" app:tabselectedtextcolor= "#ff0000" app:
Tabtextcolor= "#ffffff"/> </FrameLayout> <android.support.v4.view.viewpager android:id= "@+id/vp" Android:layout_width= "Match_paRent "android:layout_height=" match_parent "/> </LinearLayout> <declare-styleable name=" Sliderlayout " > <attr name= "slider_pic" format= "reference"/> </declare-styleable> <?xml version= "1.0" encoding= "
Utf-8 "?> <shape xmlns:android= http://schemas.android.com/apk/res/android" android:shape= "Rectangle" > <corners android:topleftradius= "10DP" android:toprightradius= "10DP" android:bottomleftradius= "10DP" Android: bottomrightradius= "10DP"/> <solid android:color= "#ffffff"/> </shape>

The above is a small set to introduce the Android Tablayout custom selection Background Slider example code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.