Android UI Tab Type interface summary

Source: Internet
Author: User
Tags getcolor

Android Program to implement tab type interface is very common, I do projects often used, so I would like to summarize here, the implementation of the tab type interface of several ways for everyone to reference. If there is something wrong, please correct me!

One, tabactivity + Tabwidget + tabhost.

To implement the tab type interface, the first thing to think about is this way. However, after API level 13, it is not recommended for official use. But let's just say a little bit about its use here.


The key to using it is the layout file. You need to add <TabHost>, <TabWidget>, <FrameLayout> these three controls to the layout, which are provided by the system: @android: Id/tabhost, @android: ID/ Tabs, @android: Id/tabcontent.

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <tabhost android:id= "@android: Id/tabhost" android:layout_width= "Match_parent" Android:layo ut_height= "Match_parent" > <relativelayout android:layout_width= "match_parent" Android: layout_height= "match_parent" android:orientation= "vertical" > <!--can specify the location of the Tabwidget Android                : Layout_alignparentbottom= "True"--<tabwidget android:id= "@android: Id/tabs" Android:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:layout_a Lignparentbottom= "false" > </TabWidget> <framelayout android:id= "@android : Id/tabcontent "AndroidOid:layout_width= "Match_parent" android:layout_height= "match_parent" android:layout_below= "@ Android:id/tabs "> <linearlayout android:id=" @+id/tab1 "Android : layout_width= "match_parent" android:layout_height= "Match_parent" Android:background = "#DEB887" android:orientation= "vertical" > </LinearLayout> <                    LinearLayout android:id= "@+id/tab2" android:layout_width= "Match_parent" android:layout_height= "Match_parent" android:background= "#BCEE68" Android:ori entation= "vertical" > </LinearLayout> <linearlayout android:i D= "@+id/tab3" android:layout_width= "match_parent" android:layout_height= "Match_paren T "anDroid:background= "#7D9EC0" android:orientation= "vertical" > </LinearLayout> </FrameLayout> </RelativeLayout> </TabHost></LinearLayout>
A linearlayout corresponds to the layout of a tab page.

Tabhost = Gettabhost (); Tabhost.addtab (Tabhost.newtabspec ("111"). Setindicator ("", Getresources (). GetDrawable ( R.drawable.wuyong)). SetContent (R.ID.TAB1)), Tabhost.addtab (Tabhost.newtabspec ("222"). Setindicator ("", Getresources (). getdrawable (R.drawable.gongsunsheng)). SetContent (R.ID.TAB2)); Tabhost.addtab (TabHost.newTabSpec ( "333"). Setindicator ("", Getresources (). getdrawable (R.drawable.likui)). SetContent (R.ID.TAB3)); Tabhost.setbackgroundcolor (Color.argb (), Tabhost.setcurrenttab (0); Tabhost.setontabchangedlistener (New Ontabchangelistener () {@Overridepublic void ontabchanged (String tabId) {Toast.maketext (Fourthactivity.this, TabId, Toast.length_short). Show ();});


Second, Viewpager + pageadapter

The most common tab interface is now implemented using Viewpager.

Let's go first. Viewpager General use steps:

1. Add the Viewpager control to the layout file

2. Set the Viewpager adapter in your code that inherits from Pageradapter or its subclasses. The following four methods must be implemented:

(1) GetCount ()

(2) Instantiateitem ()

(3) Destoryitem ()

(4) Isviewfromobject ()

3. Initialize the Viewpager control, set the listener

4. Setting the Listener event (Setonpagechangelistener)

Here's a look at this way:


The main function code is as follows:

private void Init () {Viewpager = (Viewpager) Findviewbyid (R.ID.FIRST_VP); Layoutinflater Inflater = Layoutinflater.from (this); View view1 = inflater.inflate (R.LAYOUT.FIRST_LAYOUT1, NULL); View view2 = inflater.inflate (r.layout.first_layout2, NULL); View view3 = inflater.inflate (R.LAYOUT.FIRST_LAYOUT3, null); List.add (View1); List.add (VIEW2); List.add (VIEW3); Viewpager.setadapter (Pageradapter); Viewpager.setonpagechangelistener (new Onpagechangelistener () {@Overridepublic void onpageselected (int arg0) {setdots (arg0);} @Overridepublic void onpagescrolled (int arg0, float arg1, int arg2) {} @Overridepublic void onpagescrollstatechanged (int a rg0) {}});}
Private Pageradapter Pageradapter = new Pageradapter () {
        <span style= "White-space:pre" ></span>//the official proposal so write @overridepublic Boolean isviewfromobject (View arg0, Object arg1) {return arg0 = = arg1;}   <span style= "White-space:pre" ></span>//returns a total of how many interfaces @overridepublic int GetCount () {return list.size ();} <span style= "White-space:pre" ></span>//instantiates a item@overridepublic Object Instantiateitem (ViewGroup container, int position) {Container.addview (List.get (position)); return list.get (position);} <span style= " White-space:pre "></span>//destroys a item@overridepublic void Destroyitem (ViewGroup container, int position, Object object) {Container.removeview (List.get (position));}};
The above four methods must be implemented in an adapter.

If only these pages, interactivity is certainly not good, so you need to add an "indicator" to identify the current page is which! I'm here to use some of the points to achieve. It's like the show.

/** * Initialize the bottom point */private void Initdots () {pointlayout = (linearlayout) Findviewbyid (r.id.point_layout);d ots = New ImageView [List.size ()];for (int i = 0; i < list.size (); i++) {dots[i] = (ImageView) pointlayout.getchildat (i);} Currentindex = 0;dots[currentindex].setbackgroundresource (R.drawable.dian_down);} /** * When scrolling, change the background of the point */private void setdots (int position) {if (Position < 0 | | position > list.size ()-1| | currentin Dex = = position) {return;} Dots[position].setbackgroundresource (R.drawable.dian_down);d Ots[currentindex].setbackgroundresource ( R.drawable.dian); currentindex = position;}
The point is that after the page is switched, the points are switched. This is the way to use the onpageselected (int arg0) in Onpagechangelistener.

@Overridepublic void onpageselected (int arg0) {setdots (arg0);}

Third, Fragment + Fragmentmanager

Fragment believes that you must have used them in the project. This method mainly uses Fragmentmanager to fragment's transaction management function.

Three tabs private LinearLayout tab1layout, Tab2layout, tab3layout;//default selected first tabprivate int index = 1;//Fragment Management class private F Ragmentmanager fragmentmanager;//three x fragmentprivate Fragment tab1fragment, Tab2fragment, tab3fragment;@ overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_second); Fragmentmanager = Getsupportfragmentmanager (); init ();}  /** * Initialize control */private void init () {tab1layout = (linearlayout) Findviewbyid (r.id.tab1_layout); tab2layout = (linearlayout) Findviewbyid (r.id.tab2_layout); tab3layout = (linearlayout) Findviewbyid (r.id.tab3_layout); Tab1layout.setonclicklistener (This), Tab2layout.setonclicklistener (This), Tab3layout.setonclicklistener (this);// Setdefaultfragment ();} /** * Set the default display of fragment */private void Setdefaultfragment () {fragmenttransaction transaction = Fragmentmanager.begintransaction (); tab1fragment = new Tab1fragment (); Transaction.replace (R.id.content_layout, tab1fragment); Transaction.commit ();} /** * Toggle Fragment * @param newfragment */private void replacefragment (Fragment newfragment) {fragmenttransaction transaction = Fragmentmanager.begintransaction (), if (!newfragment.isadded ()) {Transaction.replace (r.id.content_layout, newfragment); Transaction.commit ();} else {transaction.show (newfragment);}} /** * Change the check state of the phenomenon card */private void Clearstatus () {if (index = = 1) {Tab1layout.setbackgroundcolor (Getresources (). GetColor ( R.color.tab));} else if (index = = 2) {Tab2layout.setbackgroundcolor (Getresources (). GetColor (R.color.tab));} else if (index = = 3) {Tab3lay Out.setbackgroundcolor (Getresources (). GetColor (R.color.tab));}} @Overridepublic void OnClick (View v) {clearstatus (); switch (V.getid ()) {case R.id.tab1_layout:if (tab1fragment = = null) { Tab1fragment = new Tab1fragment ();} Replacefragment (tab1fragment); Tab1layout.setbackgroundcolor (Getresources (). GetColor (R.color.tab_down)); index = 1 ; break;case r.id.tab2_layout:if (tab2fragment = = null) {tab2fragment = new tab2fragment ();} Replacefragment (tab2fragment); Tab2layout.setbackgroundcolor (Getresources () GetColor (R.color.tab_down)); index = 2;break;case R.id.tab3_ Layout:if (tab3fragment = = null) {tab3fragment = new tab3fragment ();} Replacefragment (tab3fragment); Tab3layout.setbackgroundcolor (Getresources (). GetColor (R.color.tab_down)); index = 3 ; break;}}

Each fragment corresponds to a layout, click on a different button to toggle the page. Effects such as:

Four, Viewpager + Fragment + fragmentpageradapter

If you want to use fragment and you want to be able to swipe left and right, you can use this method. The main part is on the Viewpager adapter. Its adapter inherits the Fragmentpageradapter.

Package Com.tab.view.demo3;import Java.util.arraylist;import Android.support.v4.app.fragment;import Android.support.v4.app.fragmentmanager;import Android.support.v4.app.fragmentpageradapter;public Class Fragmentadapter extends Fragmentpageradapter {private arraylist<fragment> list;public fragmentadapter ( Fragmentmanager FM, arraylist<fragment> list) {super (FM); this.list = list;} @Overridepublic Fragment getItem (int arg0) {return list.get (arg0);} @Overridepublic int GetCount () {return list.size ();}}

You need to pass in the Fragmentmanager object and a list object that holds the fragment.

/** * Initialize Viewpager */private void Initviewpager () {Viewpager = (Viewpager) Findviewbyid (R.ID.THIRD_VP); fragmentsList = NE W arraylist<> (); Fragment Fragment = new Tab1fragment (); Fragmentslist.add (Fragment); Fragment = new Tab2fragment (); Fragmentslist.add ( fragment); fragment = new Tab3fragment (); Fragmentslist.add (fragment); Viewpager.setadapter (New Fragmentadapter ( Getsupportfragmentmanager (), fragmentslist); Viewpager.setcurrentitem (0); Viewpager.setonpagechangelistener (this );}


Adds a Click event to the button.

@Overridepublic void OnClick (View v) {switch (V.getid ()) {case R.id.tab1_tv:viewpager.setcurrentitem (0); break;case R.id.tab2_tv:viewpager.setcurrentitem (1); Break;case R.id.tab3_tv:viewpager.setcurrentitem (2); break;}}

I added a imageview as an indicator in the layout file. If you want the first tab type interface to be implemented in the onpageselected () method, the effect is only when the page is completely switched over before the indicator moves past. To move the indicator while sliding the page, you need to set it in the Onpagescrolled () method.

@Overridepublic void onpagescrolled (int position, float positionoffset,int positionoffsetpixels) {offset = (screen1_3-c Ursorimg.getlayoutparams (). width)/2; LOG.D ("111", Position + "--" + Positionoffset + "--" + positionoffsetpixels); final float scale = getresources (). Getdisplaym Etrics (). density;if (Position = = 0) {//0<->1lp.leftmargin = (int) (POSITIONOFFSETPIXELS/3) + offset;} else if (PO Sition = = 1) {//1<->2lp.leftmargin = (int) (POSITIONOFFSETPIXELS/3) + screen1_3 +offset;} CURSORIMG.SETLAYOUTPARAMS (LP); currentindex = position;}


The three parameters in onpagescrolled are more important. The first parameter is position. It is meant to represent the first interface in the currently displayed interface. It means that when sliding, there may be two interfaces, position refers to the left side of the interface. The second argument is that Positionoffset refers to the ratio of offsets, and the range of values is [0, 1]. The third argument is that positionoffsetpixels refers to the pixel value of the offset. The last two parameters are relative to the page (one page).

I've seen the first two parameters when setting the indicator, and I tried it, OK. But the feeling is more complicated, look at the official API, with a third parameter is simpler. The key is to understand the first parameter position. In this way I only have two judgments in the code to complete.

As follows:

Five, Viewpager + Pagertitlestrip/pagertabstrip


this way has no effect on a good looking, and the title changes. Take a look:

Layout file:

<?xml    Version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android" Android:layout_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > < Android.support.v4.view.ViewPager android:id= "@+id/fifth_vp" android:layout_width= "Wrap_content" Android oid:layout_height= "wrap_content" android:layout_gravity= "center" > <android.support.v4.view.pagertabst RIP android:id= "@+id/fifth_strip" android:layout_width= "Wrap_content" Android:layout_heig ht= "Wrap_content" android:layout_gravity= "Top" android:background= "#7EC0EE" Android:paddi ng= "10dip"/> </android.support.v4.view.viewpager></linearlayout> 

First of all, the difference between Pagertitlestrip and Pagertabstrip: Pagertitlestrip There is no indicator, only the title, and the title does not respond to events, and Pagertabstrip is marked with an indicator, and of course there are headings, with corresponding events. The implementation of the two is only in the layout file differences, only need to change the Android.support.v4.view.PagerTabStrip to Android.support.v4.viewPagerTitleStrip.
It is important to note in the code that the Getpagetitle (int) method is overridden in the adapter to display the caption.

Pageradapter pageradapter = new Pageradapter () {                //omit other methods here
Override this method to display the title @overridepublic charsequence getpagetitle (int position) {return titlelist.get (position);}};


Summarize:

I am currently encountering the tab type interface implementation is so much, if you have other ways to achieve, please leave a message. If I write the wrong, please leave a message, make progress together! Thank you!

demo:http://download.csdn.net/detail/crazy1235/8358671

Android UI Tab Type interface summary

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.