Use viewpager to implement the action tab that can slide left and right

Source: Internet
Author: User
1. Key Points of viewpager:
  • Viewpager is a layout manager that provides the Left and Right slide function for pages, similar to listview. It also provides fragmentpageradapter and fragmentstatepageradapter for viewpager ).
  • Viewpager is often used with fragment. It uses the actionbar tab to slide left and right of the tab page.
  • Viewpager belongs to the android SDK extension package, to use viewpager, need external import extension package: android-support-v4.jar
2. Implementation Functions: The functions implemented in this example are as follows:
The advantage of sliding the left and right of a tab page is that we are often used to operating the mobile phone with one hand, but it is very difficult to switch the tab page with one hand, the left and right slide function of the tab page can solve this problem and provide more convenient interaction.

3. principles: the entire application can be divided into several modules:

  • The main interface activity is mainly composed of viewpager, which contains three fragment pages and slides between the left and right;
  • Create three Tab buttons in the actionbar of the activity on the main interface );
  • The interaction between actionbar and viewpager is as follows: when viewpager enables the three fragment loaded to switch between the left and right, it controls the switch between the left and right of the corresponding action tab button. In turn, when you manually switch three Tab buttons, control the corresponding fragment switching in viewpager.
4. Procedure: 4.1 create a project and import the android-support-v4.jar extension package:

  • Create an actiontabwithslippingfragment.
  • Import android-support-v4.jar extension package: Many import methods on the Internet indicate that you want to import through "Project-properties-Java build path-add external jars", this can ensure that the compilation is passed, however, an error occurs during running! Here, the import method is as follows:
  • First create a folder libs under the project directory, and then manually copy the android-support-v4.jar to the new libs directory under "android SDK directory \ extras \ Android \ Compatibility \ V4, finally, right-click the project and select "refresh" to refresh, then you can see that the libs directory and Android dependencies Directory have android-support-v4.jar appear, which means the import is successful! As shown in:


4.2 create three fragment classes as slide tabs and manage them by viewpager ):
  • Create three fragement classes: fragment1.java, fragment2.java, and fragment3.java. Create Layout View files: fragment1.xml, fragment2.xml, and fragment3.xml respectively, and set red (R) and green (g) and blue (B) background.
  • Fragment1.java is created as follows. The key is to implement its oncreateview method and set its layout:
  • public class Fragment1 extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflateAndSetupView(inflater, container, savedInstanceState, R.layout.fragment1);}private View inflateAndSetupView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, int layoutResourceId) {View layout = inflater.inflate(layoutResourceId, container, false);return layout;} }
  • Fragment1.xml mainly defines a linearlayout with a red background:
  • <?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:background="#FF0000" >        <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_gravity="center"        android:gravity="center"        android:text="@string/frag_1"        android:textSize="30dp"        android:textStyle="bold"        android:textColor="#FFFFFF" /></LinearLayout>
4.3 create the main interface activity: actiontabwithslippingfragmentactivity and its corresponding layout file: Main. xml:
  • Set the actionbar style, such as: No rollback button or title. -- setupactionbar ()
  • Initialize and set viewpager. two key points: First, define and set the viewpageradapter, which is the data control class required by viewpager. viewpageradapter must return the fragment, page number, and page title of the corresponding position. Second, to implement the onpagechangelistener interface of viewpager, You need to navigate to the action tab button at the corresponding position when switching the current page. If necessary, you also need to implement corresponding processing in various page flip statuses (namely, the page is being turned, the page is about to be stopped, and the page is completely stopped) -- setupviewpager ()
  • Then you need to create three Tab buttons and implement the tab listening interface: This mainly refers to how to switch the corresponding page of viewpager when selecting the corresponding tab -- setuptabs ()
  • Actiontabwithslippingfragmentactivity. Java implementation
  • public class ActionTabWithSlippingFragmentActivity extends FragmentActivity implements ActionBar.TabListener{    private Fragment1 mFragment1 = new Fragment1();private Fragment2 mFragment2 = new Fragment2();private Fragment3 mFragment3 = new Fragment3();private static final int TAB_INDEX_COUNT = 3;private static final int TAB_INDEX_ONE = 0;private static final int TAB_INDEX_TWO = 1;private static final int TAB_INDEX_THREE = 2;private ViewPager mViewPager;private ViewPagerAdapter mViewPagerAdapter;/** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                setUpActionBar();        setUpViewPager();        setUpTabs();    }        private void setUpActionBar() {    final ActionBar actionBar = getActionBar();    actionBar.setHomeButtonEnabled(false);    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);    actionBar.setDisplayShowTitleEnabled(false);    actionBar.setDisplayShowHomeEnabled(false);    }        private void setUpViewPager() {    mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());        mViewPager = (ViewPager)findViewById(R.id.pager);    mViewPager.setAdapter(mViewPagerAdapter);    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {    @Override    public void onPageSelected(int position) {    final ActionBar actionBar = getActionBar();    actionBar.setSelectedNavigationItem(position);    }        @Override    public void onPageScrollStateChanged(int state) {    switch(state) {    case ViewPager.SCROLL_STATE_IDLE:    //TODO    break;    case ViewPager.SCROLL_STATE_DRAGGING:    //TODO    break;    case ViewPager.SCROLL_STATE_SETTLING:    //TODO    break;    default:    //TODO    break;    }    }    });    }        private void setUpTabs() {    final ActionBar actionBar = getActionBar();    for (int i = 0; i < mViewPagerAdapter.getCount(); ++i) {    actionBar.addTab(actionBar.newTab()    .setText(mViewPagerAdapter.getPageTitle(i))    .setTabListener(this));    }    }        @Override    protected void onDestroy() {    super.onDestroy();    }        public class ViewPagerAdapter extends FragmentPagerAdapter {public ViewPagerAdapter(FragmentManager fm) {super(fm);// TODO Auto-generated constructor stub}@Overridepublic Fragment getItem(int position) {// TODO Auto-generated method stubswitch (position) {case TAB_INDEX_ONE:return mFragment1;case TAB_INDEX_TWO:return mFragment2;case TAB_INDEX_THREE:return mFragment3;}throw new IllegalStateException("No fragment at position " + position);}@Overridepublic int getCount() {// TODO Auto-generated method stubreturn TAB_INDEX_COUNT;}    @Overridepublic CharSequence getPageTitle(int position) {String tabLabel = null;switch (position) {case TAB_INDEX_ONE:tabLabel = getString(R.string.tab_1);break;case TAB_INDEX_TWO:tabLabel = getString(R.string.tab_2);break;case TAB_INDEX_THREE:tabLabel = getString(R.string.tab_3);break;}return tabLabel;}    }@Overridepublic void onTabReselected(Tab tab, FragmentTransaction ft) {// TODO Auto-generated method stub}@Overridepublic void onTabSelected(Tab tab, FragmentTransaction ft) {// TODO Auto-generated method stubmViewPager.setCurrentItem(tab.getPosition());}@Overridepublic void onTabUnselected(Tab tab, FragmentTransaction ft) {// TODO Auto-generated method stub}}

     

  • Implementation of Main. xml:
  • <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent" >        <android.support.v4.view.ViewPager        android:id="@+id/pager"        android:layout_width="match_parent"        android:layout_height="match_parent" >    </android.support.v4.view.ViewPager></RelativeLayout>

4.4 conclusion:
  • About viewpager combined with actionbar and fragment page Slide tab function in Google's official development documentation also describes the relevant principles of this example also as a reference, For details, please refer to: http://developer.android.com/reference/android/support/v4/view/ViewPager.html
  • Open source code, no points: http://download.csdn.net/detail/ixiaobu/4743378

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.