As time goes by now the software requirements to display more and more content, so in order to better display more content on the small screen, first we will think of the bottom menu bar, but sometimes like the current headlines news client to display too much, and want to show in the main interface, so the top navigation bar is added.
Today's headlines the main part of the top navigation bar area is a navigation menu. The navigation menu is a set of labels that, in the news client, each label is a news category that corresponds to a sub-page of the Viewpager control below. When the user slides the page in the Viewpager area, the corresponding navigation menu label is also selected, the selected label is highlighted by a rectangular red box, the label text in the red box background becomes white, and the area label text outside the red box is still gray. When a user selects a tag directly in the navigation menu, Viewpager automatically switches to the corresponding sub-page. In this article the navigation menu is implemented as a separate UI control, with the class name Catagorytabstrip, inherited from Horizontalscrollview, which makes it easy to implement the left and right sliding effects of the navigation menu and linkage to the Viewpager controls below.
Let's take a look at the results of the implementation comparison:
Top navigation bar area and Viewpager area view hierarchy
Main interface Layout
<relativelayout android:id= "@+id/main_layout" android:background= "@color/activity_bg_color" Android:layout_wid Th= "Fill_parent" android:layout_height= "fill_parent" xmlns:android= "Http://schemas.android.com/apk/res/android" & Gt <relativelayout android:id= "@+id/title_bar" style= "@style/main_title_bar_style" > <framelayout android:id= "@+id/top_head_container" android:paddingleft= "10.0dip" android:paddingright= "10.0dip" Android:layout_width= "Wrap_content" android:layout_height= "Fill_parent" > <imageview android: Layout_gravity= "center_vertical" android:id= "@+id/top_head" android:contentdescription= "@s Tring/app_name "android:background=" @drawable/bg_head "android:src=" @drawable/default_round _head "android:padding=" 2.0dip "android:layout_width=" @dimen/head_size "and Roid:layout_height= "@dImen/head_size "android:scaletype=" Fitxy "/> </framelayout><imageview android:gravity=" Center "android:id=" @+id/top_more "android:contentdescription=" @string/app_name "android:layout_width=" Wrap_con Tent "android:layout_height=" Fill_parent "android:layout_marginright=" 12.0dip "android:src=" @drawable/right_dr Awer "android:scaletype=" Centerinside "android:layout_alignparentright=" true "android:layout_centervertical=" t Rue "/> <relativelayout android:id=" @+id/title_click_layout "android:paddingleft=" 13.0dip " Android:layout_width= "Wrap_content" android:layout_height= "Fill_parent" Android:layout_cente Rinparent= "true" > <framelayout android:id= "@+id/title_parent" android:layout_width= "Wrap_ Content "android:layout_height=" Wrap_content "android:layout_centervertical=" true "> <imagevieW android:layout_gravity= "center" android:id= "@+id/title_recent" android:contentde scription= "@string/app_name" android:layout_width= "Wrap_content" Android:layout_hei ght= "Wrap_content" android:src= "@drawable/title"/> </FrameLayout> < ImageView android:id= "@+id/top_refresh" android:contentdescription= "@string/app_name" Andro id:padding= "3.0dip" android:layout_width= "wrap_content" android:layout_height= "Wrap_conten T "android:src=" @drawable/refreshicon_titlebar "android:layout_torightof=" @id/title_parent "Android:layout_centervertical=" true "/> </RelativeLayout></RelativeLayout> < Relativelayout android:id= "@+id/category_layout" android:background= "@drawable/bg_category_bar" Android:la Yout_width= "Fill_parent" android:layout_height= "@dimen/top_category_height" android:layout_below= "@id/title_bar" ><imageview Android:id= "@+id/icon_category" android:layout_width= "@dimen/top_category_height" android:l ayout_height= "@dimen/top_category_height" android:src= "@drawable/ic_category_expand" Android: contentdescription= "@string/app_name" android:scaletype= "center" Android:layout_alignparentri Ght= "true" android:layout_centervertical= "true"/><linearlayout android:layout_width= "Wrap_content" android:layout_height= "@dimen/top_category_height" android:layout_toleftof= "@id/icon_category" Android:layout_alignparentleft= "true" android:layout_centervertical= "true" > <com.rainsong.to Utiaotabdemo. Categorytabstrip android:id= "@+id/category_strip" android:paddingleft= "6.0dip" Android:paddingright= "6.0dip" android:cliptopadding= "false" Android:layout_width= "Wrap_content" android:layout_height= "@dimen/top_category_height"/> </LinearLayout> </relativelayo ut> <android.support.v4.view.viewpager android:id= "@+id/view_pager" android:layout_width= "Fill_parent" android:layout_height= "Fill_parent" android:layout_below= "@id/category_layout"/></relativelayout>
Catagorytabstrip controls in activity with Viewpager controls
Mainactivity.java
Package Com.rainsong.toutiaotabdemo;import Java.util.arraylist;import Java.util.list;import android.os.Bundle; Import Android.support.v4.app.fragment;import Android.support.v4.app.fragmentactivity;import Android.support.v4.app.fragmentmanager;import Android.support.v4.app.fragmentpageradapter;import Android.support.v4.view.viewpager;public class Mainactivity extends Fragmentactivity {private Categorytabstrip tabs; Private Viewpager Pager; Private Mypageradapter adapter; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Tabs = (categorytabstrip) Findviewbyid (R.id.category_strip); Pager = (Viewpager) Findviewbyid (R.id.view_pager); adapter = new Mypageradapter (Getsupportfragmentmanager ()); Pager.setadapter (adapter); Tabs.setviewpager (pager); } public class Mypageradapter extends Fragmentpageradapter {private final List<string> catalogs = new arraylist<string> (); Public Mypageradapter (fragmentmanager FM) {super (FM); Catalogs.add (getString (r.string.category_hot)); Catalogs.add ("\u672c\u5730"); Catalogs.add (getString (R.string.category_video)); Catalogs.add (getString (r.string.category_society)); Catalogs.add (getString (r.string.category_entertainment)); Catalogs.add (getString (R.string.category_tech)); Catalogs.add (getString (r.string.category_finance)); Catalogs.add (getString (r.string.category_military)); Catalogs.add (getString (R.string.category_world)); Catalogs.add (getString (R.STRING.CATEGORY_IMAGE_PPMM)); Catalogs.add (getString (r.string.category_health)); Catalogs.add (getString (r.string.category_government)); } @Override public charsequence getpagetitle (int position) {return catalogs.get (position); } @Override public int GetCount () {return catalogs.size (); } @Override public Fragment getItem (int position) {return newsfragment.newinstance (position); } }}
Implementation code for the Catagorytabstrip control
Categorytabstrip.java
Package Com.rainsong.toutiaotabdemo;import Android.content.context;import Android.graphics.canvas;import Android.graphics.rect;import Android.graphics.drawable.drawable;import Android.support.v4.view.viewpager;import Android.support.v4.view.viewpager.onpagechangelistener;import Android.util.attributeset;import Android.util.displaymetrics;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.linearlayout;import Android.widget.TextView;public Class Categorytabstrip extends Horizontalscrollview {private Layoutinflater mlayoutinflater; Private final Pagelistener Pagelistener = new Pagelistener (); Private Viewpager Pager; Private LinearLayout Tabscontainer; private int tabcount; private int currentposition = 0; private float currentpositionoffset = 0f; Private Rect Indicatorrect; Private Linearlayout.layouTparams Defaulttablayoutparams; private int scrolloffset = 10; private int lastscrollx = 0; Private drawable indicator; Private textdrawable[] drawables; Private drawable Left_edge; Private drawable Right_edge; Public Categorytabstrip (Context context) {This (context, NULL); } public Categorytabstrip (context context, AttributeSet Attrs) {This (context, attrs, 0); } public Categorytabstrip (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); Mlayoutinflater = Layoutinflater.from (context); Drawables = new Textdrawable[3]; int i = 0; while (I < drawables.length) {Drawables[i] = new Textdrawable (GetContext ()); i++; } indicatorrect = new Rect (); Setfillviewport (TRUE); Setwillnotdraw (FALSE); Label Container Tabscontainer = new LinearLayout (context); Tabscontainer.setorientation (linearlayout.horizontal); tabScontainer.setlayoutparams (New Layoutparams (Layoutparams.match_parent, layoutparams.match_parent)); AddView (Tabscontainer); Displaymetrics DM = getresources (). Getdisplaymetrics (); Scrolloffset = (int) typedvalue.applydimension (Typedvalue.complex_unit_dip, Scrolloffset, DM); Defaulttablayoutparams = new Linearlayout.layoutparams (layoutparams.wrap_content, layoutparams.match_parent); Draw the highlighted area as a sliding paging indicator indicator = getresources (). getdrawable (R.drawable.bg_category_indicator); Left and right border shadow effect Left_edge = Getresources (). getdrawable (R.drawable.ic_category_left_edge); Right_edge = Getresources (). getdrawable (R.drawable.ic_category_right_edge); }//Bind the Viewpager control corresponding to the Categorytabstrip control, implementing the linkage public void Setviewpager (Viewpager pager) {This.pager = pager; if (pager.getadapter () = = null) {throw new IllegalStateException ("Viewpager does not has adapter inst ance. "); Pager.setonpagechangelistEner (Pagelistener); Notifydatasetchanged (); }//When the data attached to the Viewpager adapter changes, the method should be called to notify Categorytabstrip to refresh the data public void notifydatasetchanged () {Tabscontain Er.removeallviews (); Tabcount = Pager.getadapter (). GetCount (); for (int i = 0; i < Tabcount; i++) {AddTab (I, Pager.getadapter (). Getpagetitle (i). toString ()); }}//Add a label to the navigation menu private void AddTab (final int position, String title) {viewgroup tab = (viewgroup) mlay Outinflater.inflate (R.layout.category_tab, this, false); TextView Category_text = (TextView) Tab.findviewbyid (R.id.category_text); Category_text.settext (title); Category_text.setgravity (Gravity.center); Category_text.setsingleline (); Category_text.setfocusable (TRUE); Category_text.settextcolor (Getresources (). GetColor (R.color.category_tab_text)); Tab.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { Pager.setcurrentitem (position); } }); Tabscontainer.addview (tab, position, defaulttablayoutparams); }//calculates the upper and lower left and right positions of the rectangle's highlighted area in the sliding process private void calculateindicatorrect (rect rect) {ViewGroup Currenttab = (viewgroup) Tabscontainer.getchildat (currentposition); TextView Category_text = (TextView) Currenttab.findviewbyid (R.id.category_text); float left = (float) (Currenttab.getleft () + category_text.getleft ()); Float width = ((float) category_text.getwidth ()) + left; if (Currentpositionoffset > 0f && currentposition < tabCount-1) {ViewGroup Nexttab = (Viewgrou p) Tabscontainer.getchildat (currentposition + 1); TextView Next_category_text = (TextView) Nexttab.findviewbyid (R.id.category_text); float next_left = (float) (Nexttab.getleft () + next_category_text.getleft ()); left = left * (1.0f-currentpositionoffset) + next_left * CURRENTPOSITIONOFFSET;width = width * (1.0f-currentpositionoffset) + Currentpositionoffset * ((float) next_category_text.getwidth ()) + next_l EFT); } rect.set ((int) left) + Getpaddingleft (), getpaddingtop () + currenttab.gettop () + category_text.gettop (), ((int) width) + getpaddingleft (), currenttab.gettop () + getpaddingtop () + category_text.gettop () + CATEGORY_TEXT.G Etheight ()); }//Calculate scroll range private int getscrollrange () {return getchildcount () > 0? Math.max (0, Getchildat (0). GetWidth ()-getwidth () + getpaddingleft () + getpaddingright ()): 0; }//Categorytabstrip and Viewpager linkage logic private void scrolltochild (int position, int offset) {if (Tabcount = = 0) {return; } calculateindicatorrect (Indicatorrect); int newscrollx = LASTSCROLLX; if (Indicatorrect.left < GETSCROLLX () + scrolloffset) {newscrollx = Indicatorrect.left-scrolloffset; } else if (Indicatorrect.right > getscrollx () +GetWidth ()-Scrolloffset) {newscrollx = Indicatorrect.right-getwidth () + Scrolloffset; } if (newscrollx! = lastscrollx) {lastscrollx = NEWSCROLLX; ScrollTo (NEWSCROLLX, 0); }}//Custom drawing @Override public void Draw (canvas canvas) {super.draw (canvas); Draw a bright background rectangle red box Calculateindicatorrect (Indicatorrect); if (indicator! = null) {indicator.setbounds (indicatorrect); Indicator.draw (canvas); }//Draw background red box inside label text int i = 0; while (I < Tabscontainer.getchildcount ()) {if (I < currentPosition-1 | | i > currentposition + 1) { i++; } else {viewgroup tab = (viewgroup) tabscontainer.getchildat (i); TextView Category_text = (TextView) Tab.findviewbyid (R.id.category_text); if (category_text! = null) {textdrawable textdrawable = Drawables[i-currentposItion + 1]; int save = Canvas.save (); Calculateindicatorrect (Indicatorrect); Canvas.cliprect (Indicatorrect); Textdrawable.settext (Category_text.gettext ()); Textdrawable.settextsize (0, Category_text.gettextsize ()); Textdrawable.settextcolor (Getresources (). GetColor (R.color.category_tab_highlight_text)); int left = Tab.getleft () + category_text.getleft () + (Category_text.getwidth ()-textdrawable.getintrinsicwidth ())/2 + G Etpaddingleft (); int top = Tab.gettop () + category_text.gettop () + (Category_text.getheight ()-textdrawable.getintrinsicheight ())/2 + GE Tpaddingtop (); Textdrawable.setbounds (left, Top, textdrawable.getintrinsicwidth () + left, textdrawable.getintrinsicheight () + top); Textdrawable.draw (canvas); Canvas.restoretocount (save); } i++; }}//Draw left and right border shadow effect i = Canvas.save (); int top = GETSCROLLX (); int height = getheight (); int width = getwidth (); Canvas.translate (float) top, 0.0f); if (Left_edge = = NULL | | Top <= 0) {if (Right_edge = = NULL | | Top >= getscrollrange ()) { Canvas.restoretocount (i); } right_edge.setbounds (Width-right_edge.getintrinsicwidth (), 0, width, height); Right_edge.draw (canvas); Canvas.restoretocount (i); } left_edge.setbounds (0, 0, left_edge.getintrinsicwidth (), height); Left_edge.draw (canvas); if (Right_edge = = NULL | | Top >= getscrollrange ()) {canvas.restoretocount (i); } right_edge.setbounds (Width-right_edge.getintrinsicwidth (), 0, width, height); Right_edge.draw (canvas); Canvas.restoretocount (i); } Private class Pagelistener implements Onpagechangelistener {@Override public void onpagescrolled (int position, float positionoffset, int positionoffsetpixels) {currentposition = position; Currentpositionoffset = Positionoffset; Scrolltochild (position, (int) (Positionoffset * Tabscontainer.getchildat (position). GetWidth ())); Invalidate (); } @Override public void onpagescrollstatechanged (int.) {if (state = = Viewpager.scroll_state _idle) {if (Pager.getcurrentitem () = = 0) {//swipe to the leftmost scrollTo (0, 0); } else if (pager.getcurrentitem () = = tabCount-1) {//swipe to the far right scroll to (Getscrollrange (), 0); } else {Scrolltochild (Pager.getcurrentitem (), 0); }}} @Override public void onpageselected (int position) {}}}
full Project source code csdn resource Download Toutiaotabdemo
Android faux-top navigation bar effect of today's headlines