ScrollView + Viewpager to achieve Android app main interface effect

Source: Internet
Author: User

ScrollView + Viewpager to achieve Android app main interface effect

The main interface of Android is usually made up of two parts: navigation bar, sliding split screen (I call it myself). Where the sliding split screen is definitely used with the fragment, the specific bearer of the control is Viewpager. There are many controls for navigating the page bar, either Tabhost,scrollview or custom.

Personally think that Tabhost and ScrollView are relatively good, because the later extensibility is better, unless the navigation bar interface does belong to the "custom" category, basically we can choose both.

The effect of the implementation is:


Of course, the effect of the demo ScrollView below a blue line, left and right arrows, which are implemented in addition. The effect of the implementation is relatively simple.

First, the implementation of ScrollView XML layout code:

The XML code for the ScrollView implementation:

<relativelayout android:id= "@+id/rl_tab" android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:background= "#F2F2F2" > <com.example.viewpager_fragment_demo.view.synchorizonta Lscrollview android:id= "@+id/mhsv" android:layout_width= "Fill_parent" android:layout_height=               "58dip" android:fadingedge= "None" android:scrollbars= "None" > <relativelayout Android:id= "@+id/rl_nav" android:layout_width= "fill_parent" android:layout_height= "wrap _content "android:layout_gravity=" Top "android:background=" #5AB0EB "> <r                    Adiogroup android:id= "@+id/rg_nav_content" android:layout_width= "Fill_parent" android:layout_height= "58dip" android:layout_alignparenttop= "true" Android Oid:background= "#F2F2F2"                    android:orientation= "Horizontal" > </RadioGroup> <imageview Android:id= "<relativelayout android:id=" @+id/rl_tab "android:layout_width=" fill_parent "Android:layout_height=" wrap_content "android:background=" #F2F2F2 "> <com.example.viewpager_f           Ragment_demo.view.SyncHorizontalScrollView android:id= "@+id/mhsv" android:layout_width= "Fill_parent"             android:layout_height= "58dip" android:fadingedge= "None" android:scrollbars= "None" >               <relativelayout android:id= "@+id/rl_nav" android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:layout_gravity= "Top" android:background= "#5AB 0EB "> <radiogroup android:id=" @+id/rg_nav_content "Android:lay Out_width= "Fill_parent"                   android:layout_height= "58dip" android:layout_alignparenttop= "true"                 Android:background= "#F2F2F2" android:orientation= "Horizontal" > </RadioGroup> <imageview android:id= "@+id/iv_nav_indicator" Android:layout_widt                    H= "1dip" android:layout_height= "5dip" android:layout_alignparentbottom= "true"                    Android:background= "#5AB0EB" android:contentdescription= "@string/nav_desc" android:scaletype= "Matrix"/> </RelativeLayout> </com.example.viewpager_fragment_demo.vie w.synchorizontalscrollview> <imageview android:id= "@+id/iv_nav_left" Android:layout_widt           H= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentleft= "true" Android:layout_centerverTical= "true" android:contentdescription= "@string/nav_desc" android:paddingbottom= "1dip" and roid:src= "@drawable/iv_navagation_scroll_left" android:visibility= "Gone" > </ImageView> & Lt;imageview android:id= "@+id/iv_nav_right" android:layout_width= "Wrap_content" Android:layo           ut_height= "Wrap_content" android:layout_alignparentright= "true" android:layout_centervertical= "true" android:contentdescription= "@string/nav_desc" android:paddingbottom= "1dip" android:src= "@draw Able/iv_navagation_scroll_right "android:visibility=" visible "> </ImageView> </relativelayou T> "android:layout_width=" 1dip "android:layout_height=" 5dip "a Ndroid:layout_alignparentbottom= "true" android:background= "#5AB0EB" Android:contentd escription= "@string/nav_Desc "android:scaletype=" Matrix "/> </RelativeLayout> &LT;/COM.EXAMPLE.VIEWPA           ger_fragment_demo.view.synchorizontalscrollview> <imageview android:id= "@+id/iv_nav_left" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_alignparentl           Eft= "true" android:layout_centervertical= "true" android:contentdescription= "@string/nav_desc" Android:paddingbottom= "1dip" android:src= "@drawable/iv_navagation_scroll_left" android:visibility= "G One "> </ImageView> <imageview android:id=" @+id/iv_nav_right "android:layout           _width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentright= "true" Android:layout_centervertical= "true" android:contentdescription= "@string/nav_desc" Android:paddi         Ngbottom= "1dip"  android:src= "@drawable/iv_navagation_scroll_right" android:visibility= "visible" > </imageview>& Lt;/relativelayout>

in the source code, through the automatic additions and deletions radiogroup to dynamic maintenance, the following imageview is @+id/iv_nav_indicator, is used to achieve the slide line hint, about the two imageview distribution on both sides.

Second, the ScrollView can dynamically delete the source code implementation:

In the source code, the specific additions and deletions radiogroup can refer to the following code:

Public Classmainactivity extends Fragmentactivity {public static final String arguments_name= "Arg";    Private Relativelayout Rl_nav;    Privatesynchorizontalscrollview MHSV;    Private Radiogroup rg_nav_content;    Private ImageView Iv_nav_indicator;    Private ImageView Iv_nav_left;    Private ImageView iv_nav_right;    Private Viewpager Mviewpager; private int indicatorwidth;    Indicator width private layoutinflater minflater;    Private Tabfragmentpageradaptermadapter;    private int currentindicatorleft= 0; public static string[] Tabtitle = {"Option 1", "Option 2", "option 3", "Option 4", "option 5",};//title @Override protected void O       Ncreate (bundlesavedinstancestate) {super.oncreate (savedinstancestate);       Setcontentview (R.layout.activity_main);       Findviewbyid ();       Initview ();    Setlistener ();       } private void Findviewbyid () {Rl_nav = (relativelayout) Findviewbyid (R.ID.RL_NAV);       MHSV = (Synchorizontalscrollview) Findviewbyid (R.ID.MHSV); RG_nav_content = (radiogroup) Findviewbyid (r.id.rg_nav_content);       Iv_nav_indicator = (ImageView) Findviewbyid (r.id.iv_nav_indicator);       Iv_nav_left = (ImageView) Findviewbyid (r.id.iv_nav_left);       Iv_nav_right = (ImageView) Findviewbyid (r.id.iv_nav_right);    Mviewpager = (Viewpager) Findviewbyid (R.id.mviewpager);       } private void Initview () {displaymetricsdm = Newdisplaymetrics (); Getwindowmanager (). Getdefaultdisplay (). Getmetrics (DM);//Get screen info indicatorwidth = dm.widthpixels/4;//indicator width is 4 of screen width       1 layoutparamscursor_params = Iv_nav_indicator.getlayoutparams ();        Cursor_params.width = indicatorwidth;//initializes the width iv_nav_indicator.setlayoutparams (cursor_params) of the sliding cursor;       Mhsv.setsomeparam (Rl_nav, Iv_nav_left, Iv_nav_right, this, dm.widthpixels);        Gets the layout filler Minflater = (layoutinflater) this. Getsystemservice (Layout_inflater_service);        INITNAVIGATIONHSV (); Madapter = Newtabfragmentpageradapter(Getsupportfragmentmanager ());    Mviewpager.setadapter (Madapter);        } private void Initnavigationhsv () {rg_nav_content.removeallviews ();                  for (int i = 0; i < tabtitle.length; i++) {RADIOBUTTONRB = (RadioButton) minflater.inflate (           R.layout.nav_radiogroup_item,null);           Rb.setid (i);           Rb.settext (Tabtitle[i]);            Rb.setlayoutparams (New Layoutparams (Indicatorwidth, layoutparams.match_parent));       Rg_nav_content.addview (RB); }} public class Tabfragmentpageradapterextendsfragmentpageradapter {Publictabfragmentpageradapter (Fragment       Manager FM) {super (FM);           } @Override public Fragment getItem (int arg) {fragmentft = null;              Switch (ARG) {case 0:ft= newlaunchuifragment ();           Break              Case 2:ft= Newspecialuifragment (mainactivity.this);           Break Default: ft= newcommonuifragment ();              Bundleargs = Newbundle ();              Args.putstring (Arguments_name,tabtitle[arg]);              Ft.setarguments (args);           Break       } return ft;       } @Override public int getcount () {return tabtitle.length; }} private void Setlistener () {Mviewpager.setonpagechangelistener (new Onpagechangelistener () {@O                     Verride public void onpageselected (int position) {if (rg_nav_content! = null &&rg_nav_content.getchildcount () > Position) {(RadioButton) Rg_nav_content.getchildat (position              ). PerformClick ();            }} @Override public void onpagescrolled (int arg0, float arg1, int arg2) {}       @Override public voidonpagescrollstatechanged (int arg0) {}});           Rg_nav_content   . Setoncheckedchangelistener (Newoncheckedchangelistener () {@Override public voidonch                          Eckedchanged (radiogroup Group, int checkedid) {if (Rg_nav_content.getchildat (checkedid)! = null) { Translateanimationanimation = Newtranslateanimation (currentindicator Left, ((RadioButton) rg_nav_content Getchildat (Checke                         did)). GetLeft (), 0f,0f);                         Animation.setinterpolator (New Linearinterpolator ());                         Animation.setduration (100);                          Animation.setfillafter (TRUE);                          Perform displacement animation iv_nav_indicator.startanimation (animation);                          Mviewpager.setcurrentitem (Checkedid);//Viewpager//follow together switch //record the distance from the leftmost side of the current subscript currentindicatorleft= (RadioButton) rg_nav_content                          . Getchildat (Checkedid)). GetLeft (); Mhsv.smoothscrollto ((checkedid> 1?)                                       ((RadioButton) rg_nav_content. Getchildat (Checkedid)). GetLeft ()                                              : 0)-((RadioButton) rg_nav_content                     . Getchildat (2)). GetLeft (), 0);    }                  }              }); }}

Third, the Viewpager XML layout implementation:

And with the following Viewpager, is mainly carrying fragment. Therefore, it is relatively simple. Look at the layout:

<android.support.v4.view.viewpager        android:id= "@+id/mviewpager"        android:layout_width= "Wrap_content"        android:layout_height= "wrap_content"        android:layout_alignparentbottom= "true"        Android:layout_below = "@id/rl_tab"        android:layout_gravity= "center"        android:background= "#ffffff"        android:flipinterval= " "        android:persistentdrawingcache=" animation "/>

Four, the custom horizontal sliding scrollview The small arrow hint the source code realization:

in the source see its implementation can also refer to the above code. Where the custom transverse sliding scrollview is mainly handled in the scrollview transverse sliding, the left and right two small arrows hide and show the situation. Refer to the following code:

Public Classsynchorizontalscrollview extends Horizontalscrollview {Publicsynchorizontalscrollview (context context) {    Super (context);    } publicsynchorizontalscrollview (Context context, AttributeSet Attrs) {Super (context, attrs); } publicsynchorizontalscrollview (Context context, AttributeSet attrs, int defstyle) {Super (context, a    Ttrs,defstyle);    } private View view; Private ImageView leftimage;//Zoope picture Private ImageView rightimage;//right label picture private int WINDOWWITDH = 0;//screen width priv     Ate Activity mcontext; public void Setsomeparam (View view,imageview iv_nav_left, Imageviewiv_nav_right, Activity context, int Widthpixe       ls) {this.view = view;       This.mcontext = context;       This.leftimage = Iv_nav_left;       This.rightimage = Iv_nav_right;    THIS.WINDOWWITDH = Widthpixels; } @Override protected void onscrollchanged (int l, int t, int oldl, int Oldt) {super.onscrollchanged (L, T,old L, Oldt);           if (!mcontext.isfinishing () && view!= null&& rightimage!= null &&leftimage!= null) {              if (View.getwidth () <= WINDOWWITDH) {leftimage.setvisibility (view.gone);           Rightimage.setvisibility (View.gone);                  }else{if (L = = 0) {leftimage.setvisibility (view.gone);              Rightimage.setvisibility (view.visible);                  }elseif (View.getwidth ()-L = = WINDOWWITDH) {leftimage.setvisibility (view.visible);              Rightimage.setvisibility (View.gone);                  }else{leftimage.setvisibility (view.visible);              Rightimage.setvisibility (view.visible); }           }        }    } }


Basically here, scrollview+ Viewpager achieve the Android main interface effect is achieved. The rotation of the slide line corresponds to the above code:rg_nav_content . Setoncheckedchangelistener Place, which is basically complete.

The above source demo download

ScrollView + Viewpager to achieve Android app main interface effect

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.