Android UI: Tab interface summary, androidui

Source: Internet
Author: User
Tags getcolor

Android UI: Tab interface summary, androidui

Reprinted please indicate the source: http://blog.csdn.net/crazy1235/article/details/42678877


It is very common to implement the Tab interface in the Android program, which is often used in projects. So I would like to summarize several methods to implement the tab interface for your reference. If anything is wrong, please correct me!

1. TabActivity + TabWidget + TabHost.

This method is the first method to implement the TAB interface. However, after API level 13, it is not officially recommended. However, let's briefly describe how to use it here.


The key to using it is the layout file. You must add the <TabHost>, <TabWidget>, and <FrameLayout> controls in the layout. The IDS are provided by the system: @ android: id/tabhost, and @ 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: layout_height = "match_parent"> <RelativeLayout android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientat Ion = "vertical"> <! -- You can specify the location of tabwidget android: layout_alignParentBottom = "true" --> <TabWidget android: id = "@ android: id/tabs" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: layout_alignParentBottom = "false"> </TabWidget> <FrameLayout android: id = "@ android: id/tabcontent" android: 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: orientation = "vertical"> </LinearLayout> <LinearLayout android: id = "@ + id/tab3" android: layout_width = "match_parent" android: layout_height = "match_parent" 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(150, 22, 70, 150));tabHost.setCurrentTab(0);tabHost.setOnTabChangedListener(new OnTabChangeListener() {@Overridepublic void onTabChanged(String tabId) {Toast.makeText(FourthActivity.this, tabId, Toast.LENGTH_SHORT).show();}});


Ii. ViewPager + PageAdapter

Currently, viewpager is the most common tab interface.

The general procedure of viewpager is as follows:

1. Add the viewpager control to the layout file.

2. Set the viewpager adapter in the Code. This class inherits from pagerAdapter or its subclass. The following four methods must be implemented:

(1) getCount ()

(2) instantiateItem ()

(3) destoryItem ()

(4) isViewFromObject ()

3. initialize the viewpager control and set the listener.

4. setOnPageChangeListener)

Let's take a look at this method:


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 arg0) {}});}
private PagerAdapter pagerAdapter = new PagerAdapter() {
<Span style = "white-space: pre"> </span> // The official suggestion is as follows: @ Overridepublic boolean isViewFromObject (View arg0, Object arg1) {return arg0 = arg1 ;}< span style = "white-space: pre"> </span> // returns the total number of interfaces @ Overridepublic int getCount () {return list. size () ;}< span style = "white-space: pre"> </span> // instantiate an item @ Overridepublic Object instantiateItem (ViewGroup container, int position) {container. addView (list. get (position); return list. get (position) ;}< span style = "white-space: pre"> </span> // destroy an item @ Overridepublic void destroyItem (ViewGroup container, int position, object object) {container. removeView (list. get (position ));}};
The above four methods must be implemented in the adapter.

If there are only a few pages, the interaction is definitely not good, so you need to add a "indicator" to identify which one is the current page! Here I use vertices for implementation. As shown in.

/*** Initialize the bottom vertex */private void initDots () {pointLayout = (LinearLayout) findViewById (R. id. point_layout); dots = 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);}/*** change the background image of the vertex when rolling */private void setDots (int position) {if (position <0 | position> list. size ()-1 | currentIndex = position) {return;} dots [position]. setBackgroundResource (R. drawable. dian_down); dots [currentIndex]. setBackgroundResource (R. drawable. dian); currentIndex = position ;}
The point is that after page switching, the point also needs to be switched. At this time, the onPageSelected (int arg0) method in OnPageChangeListener is used.

@Overridepublic void onPageSelected(int arg0) {setDots(arg0);}

Iii. Fragment + FragmentManager

 

Fragment is believed to have been used in projects. This method uses fragmentManager to manage fragment transactions.

// Three tabs: private LinearLayout tab1Layout, tab2Layout, and tab3Layout; // The first tabprivate int index = 1 is selected by default; // fragment management class: private FragmentManager fragmentManager; // three fragmentprivate Fragment tab1Fragment, tab2Fragment, tab3Fragment; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_second); fragmentManager = getSupportFragmentMana Ger (); init ();}/*** initialization 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); // setdefafrfragment ();}/*** sets the default display fragment */private void setDe FaultFragment () {FragmentTransaction transaction = fragmentManager. beginTransaction (); tab1Fragment = new Tab1Fragment (); transaction. replace (R. id. content_layout, tab1Fragment); transaction. commit ();}/*** switch 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) ;}}/*** changes the selected status of the symptom 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) {tab3Layout. 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 a different button to switch the page. The effect is as follows:

 

4. ViewPager + Fragment + FragmentPagerAdapter

This method can be used if you want to slide left and right when using fragment. The main part is the adapter of viewpager. Its adapter inherits 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 input the FragmentManager object and a list object that stores fragment.

/*** Initialize viewpager */private void initViewPager () {viewPager = (ViewPager) findViewById (R. id. third_vp); fragmentsList = new 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 );}


Add 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 an imageview to the layout file as an indicator. If you want to set the implementation method of the first tab interface in the onPageSelected () method, the effect is that the indicator can be moved only after the page is completely switched over. To move the indicator while sliding the page, you must set it in the onPageScrolled () method.

@Overridepublic void onPageScrolled(int position, float positionOffset,int positionOffsetPixels) {offset = (screen1_3 - cursorImg.getLayoutParams().width) / 2;Log.d("111", position + "--" + positionOffset + "--"+ positionOffsetPixels);final float scale = getResources().getDisplayMetrics().density;if (position == 0) {// 0<->1lp.leftMargin = (int) (positionOffsetPixels / 3) + offset;} else if (position == 1) {// 1<->2lp.leftMargin = (int) (positionOffsetPixels / 3) + screen1_3 +offset;}cursorImg.setLayoutParams(lp);currentIndex = position;}


The three parameters in onPageScrolled are important. The first parameter is position. It indicates the first interface in the currently displayed interface. This means that when sliding, there may be two interfaces, position refers to the interface on the left. The second parameter is positionOffset, which refers to the offset ratio. The value range is [0, 1 ). The third parameter is positionOffsetPixels, which refers to the offset pixel value. The last two parameters are relative to the page.

I have seen the first two parameters used to set the indicator before. I also tried, OK. However, it seems complicated. After reading the official api, it is easier to use the third parameter. The key is to understand the first parameter position. In this way, I can only make two judgments in the code.

As follows:

 

5. Viewpager + PagerTitleStrip/PagerTabStrip


This method does not look good 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:layout_height="wrap_content"        android:layout_gravity="center" >        <android.support.v4.view.PagerTabStrip            android:id="@+id/fifth_strip"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="top"            android:background="#7EC0EE"            android:padding="10dip" />    </android.support.v4.view.ViewPager></LinearLayout>

Let's take a look at the difference between PagerTitleStrip and PagerTabStrip: PagerTitleStrip has no indicator, only the title, and the title does not respond to the event. PagerTabStrip has an indicator, and of course there is a title and a corresponding event. The implementation of the two is only different in the layout file. You only need to change android. support. v4.view. PagerTabStrip to android. support. v4.viewPagerTitleStrip.
Note that the getPageTitle (int) method is rewritten in the adapter to display the title.

PagerAdapter pagerAdapter = new PagerAdapter () {// other methods are omitted here
// Rewrite this method to display the title @ Overridepublic CharSequence getPageTitle (int position) {return titleList. get (position );}};


Summary:

I have encountered so many implementation methods for the tab interface. If you have other implementation methods, please leave a message. If I write something wrong, please leave a message to correct it and make progress together! Thank you!

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

 

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.