How to Create Android Tabbed style with Page Swipe View

给你一囗甜甜゛ 提交于 2019-11-28 04:58:31

This article (Android Material Design working with Tabs) published on September 13, 2015 guides you through creating tab pages.

For example, creating Fixed Tabs

Fixed tabs should be used when you have limited number of tabs. These tabs are fixed in position. In android design support library lot of new elements like CoordinatorLayout, AppBarLayout, TabLayout and lot more were introduced. I won’t cover all of these as it’s not the agenda of this article.

Open the layout file of main activity (activity_main.xml) and add below layout code.

app:tabMode – Defines the mode of the tab layout. In our case the value should be “fixed”

activity_main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</android.support.design.widget.CoordinatorLayout>

Open MainActivity.java and do the below changes.

tabLayout.setupWithViewPager() – Assigns the ViewPager to TabLayout.

setupViewPager() – Defines the number of tabs by setting appropriate fragment and tab name.

ViewPagerAdapter – Custom adapter class provides fragments required for the view pager. MainActivity.java

package info.androidhive.materialtabs.activity;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

import info.androidhive.materialtabs.R;
import info.androidhive.materialtabs.fragments.OneFragment;
import info.androidhive.materialtabs.fragments.ThreeFragment;
import info.androidhive.materialtabs.fragments.TwoFragment;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "ONE");
        adapter.addFragment(new TwoFragment(), "TWO");
        adapter.addFragment(new ThreeFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

Now run the app. You should able to see the tabs displayed with swipe functionality between the tabs.

First you need to create an xml layout file with viewpager android.support.v4.view.ViewPager

Then inflate this layout in your main activity, make sure your activity implements

android.support.v7.app.ActionBar.TabListener Lets say, you want to have 4 tabs, then create

4 different fragments. Create a common adapter to facilitate these fragments based on the

tabs you select.

Here is the simple example with code snippet, http://www.feelzdroid.com/2014/10/android-action-bar-tabs-swipe-views.html

Note: above example works well with android support lib, which provides backward actionbar

compatibility for earlier version of android phones

Hope it helps.

Thanks

When I had implemented something similar, I had done it in a nicer way, in the sense of classes. I had created the adapter in a package called working.

Below is the code:

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

        switch (index) {
        case 0:
          return new WorkingFragment();
        //You can add as many fragments as you wish here by adding the cases and calling the different fragments.
        }      
        return null;
    }

    @Override
    public int getCount() {
        // get item count - equal to number of tabs. 4 is only the number of fragments I had used.
        return 4;
    }
}

You then need to create a new class called WorkingFragment in the example I am giving. For the sake of clean coding, I created this class in the main package.

Below is the code for the fragment:

public class NewEventFragment extends Fragment {

    View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //reference the xml file containing the view with all the code here.
    }
}

In the MainActivity, you then need to make the functionality to change form one tab to another. In my case I had included this in the main package.

Below is the code for the MainActivity class:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

    private ViewPager ViewPager;
    private TabsPagerAdapter SectionsPagerAdapter;
    private ActionBar actionBar;

    //Include the name for the tabs in this array. Make sure the number of elements in this string matches the number of views you will have in your app. 
    private String[] tabs = {};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

     // Initialisation
        ViewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        SectionsPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        ViewPager.setAdapter(SectionsPagerAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 

     // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
        }

        ViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {

    }

    @Override
    public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
        ViewPager.setCurrentItem(tab.getPosition());

    }

    @Override
    public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
    }
} 

Hope this has helped you achieve the necessary funtionality for your app :)

simple way to work with fragment tabs

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

in on create and then

private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new 
        ViewPagerAdapter(getSupportFragmentManager());        
        adapter.addFrag(new RootDetailFragment(), "TAB 1");
        adapter.addFrag(new ShiftDetailFragment(), "TAB 2");        
        viewPager.setAdapter(adapter);
}


class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

in layout file add

 <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000"
        app:tabGravity="fill"
        app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!