Android开发

Android中实现可滑动的Tab的3种方式

本文主要是介绍Android中实现可滑动的Tab的3种方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 第一种,使用 TabHost + ViewPager 实现
该方法会有一个Bug,当设置tabHost.setCurrentTab()为0时,ViewPager不显示(准确的说是加载),只有点击其他任意一个tab后才会加载。

有解的同学吼一声~~~~~~~

Activity:

复制代码 代码如下:

package com.swordy.demo.android.fragment;

import java.util.Random;

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.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;

import com.swordy.demo.android.R;
import com.swordy.library.android.util.ELog;

/**
 * 1. 使用TabHost和ViewPager组合实现一个可以滑动的tab
 * 2. bug:如果当前页为0,则ViewPager第一次不加载。
 *
 * @author swordy
 * @email mryangjian@live.com
 * @since Jan 20, 2014
 * @version 1.0
 */
public class SlideTabs1 extends FragmentActivity
{
    private static final String TAG = "AndroidDemos.SlideTabs1";

    private TabHost mTabHost;

    private ViewPager mViewPager;

    private PagerAdapter mPagerAdapter;

    private String[] addresses = { "first", "second", "third" };

    @Override
    protected void onCreate(Bundle arg0)
    {
        super.onCreate(arg0);
        setContentView(R.layout.fragment_slidetabs1);

        mViewPager = (ViewPager) findViewById(R.id.viewPager1);
        mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);

        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup();
        mTabHost.addTab(mTabHost.newTabSpec("one").setIndicator("one-1")
                .setContent(R.id.viewPager1));
        mTabHost.addTab(mTabHost.newTabSpec("two").setIndicator("two-2")
                .setContent(R.id.viewPager1));
        mTabHost.addTab(mTabHost.newTabSpec("three").setIndicator("three-3")
                .setContent(R.id.viewPager1));

        TabWidget tabWidget = mTabHost.getTabWidget();
        int count = tabWidget.getChildCount();
        for (int i = 0; i != count; i++)
        {
            final int index = i;
            tabWidget.getChildAt(i).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v)
                {
                    mTabHost.setCurrentTab(index);
                    mViewPager.setCurrentItem(index);
                }
            });
        }
        mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

            @Override
            public void onTabChanged(String tabId)
            {
                ELog.i(TAG, "@--> onTabChanged by tabId: " + tabId);
            }
        });

        mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0)
            {
                ELog.i(TAG, "@--> onPageSelected: " + arg0);
                mTabHost.setCurrentTab(arg0);
            }

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

            }

            @Override
            public void onPageScrollStateChanged(int arg0)
            {

            }
        });
    }

    private class MyPagerAdapter extends FragmentStatePagerAdapter
    {

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

        @Override
        public Fragment getItem(int position)
        {
            ELog.i(TAG, "@--> getItem by position" + position);
            ELog.i(TAG, "@--> getItem by position" + position);
            return MyFragment.create(addresses[position]);
        }

        @Override
        public int getCount()
        {
            return addresses.length;
        }

    }

    public static class MyFragment extends Fragment
    {
        public static MyFragment create(String address)
        {
            ELog.i(TAG, "@--> MyFragment.create()");
            MyFragment f = new MyFragment();
            Bundle b = new Bundle();
            b.putString("address", address);
            f.setArguments(b);
            return f;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
        {
            Random r = new Random(System.currentTimeMillis());

            Bundle b = getArguments();

            View v = inflater.inflate(R.layout.fragment_viewpager1_layout1, null);
            v.setBackgroundColor(r.nextInt() >> 8 | 0xFF << 24);

            TextView txvAddress = (TextView) v.findViewById(R.id.textView1);
            txvAddress.setTextColor(r.nextInt() >> 8 | 0xFF << 24);
            txvAddress.setBackgroundColor(r.nextInt() >> 8 | 0xFF << 24);

            txvAddress.setText(b.getString("address", ""));
            return v;
        }

    }
}

布局:

复制代码 代码如下:

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right|center_vertical" />

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <android.support.v4.view.ViewPager
                android:id="@+id/viewPager1"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </FrameLayout>
    </LinearLayout>

</TabHost>

2. 第二种,使用官方提供的方法 ActionBar + ViewPager 实现

该方法有两个缺陷,或者说不是缺陷,只是我没有找到解决的办法。

第一,tab点上不是很灵敏,可能就是这么设定的,为了防止频繁加载吧,但是体验稍稍不爽;

第二,ActionBar在最顶部,如果我的布局是:顶部一个带返回按钮的标题栏,中间是tab,底部是tabcontent,怎么搞?

Activity:

复制代码 代码如下:

package com.swordy.demo.android.fragment;

import java.util.Random;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
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;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.swordy.demo.android.R;

/**
 * 1. 使用ActionBar和ViewPager实现可以滑动的Tab
 *
 * @author swordy
 * @email mryangjian@live.com
 * @since Jan 20, 2014
 * @version 1.0
 */
public class SlideTabs2 extends FragmentActivity
{
    private static final String TAG = "AndroidDemos.SlideTabs2";

    private ViewPager mViewPager;

    private ActionBar mActionBar;

    private MyPagerAdapter mPagerAdapter;

    private String[] addresses = { "first", "second", "third" };

    private Tab[] mTabs = new Tab[addresses.length];

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_viewpager1);
        mViewPager = (ViewPager) findViewById(R.id.viewPager1);
        mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOnPageChangeListener(mPageChangeListener);

        mActionBar = getActionBar();
        mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        mActionBar.setDisplayShowTitleEnabled(false);
        mActionBar.setDisplayShowHomeEnabled(false);

        for (int i = 0; i != addresses.length; i++)
        {
            mTabs[i] = mActionBar.newTab().setText(addresses[i]).setTabListener(mTabListener);
            mActionBar.addTab(mTabs[i]);
        }

    }

    private OnPageChangeListener mPageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0)
        {
            mActionBar.setSelectedNavigationItem(arg0);
        }

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

        }

        @Override
        public void onPageScrollStateChanged(int arg0)
        {

        }
    };

    private TabListener mTabListener = new TabListener() {

        @Override
        public void onTabSelected(Tab tab, android.app.FragmentTransaction ft)
        {
            if (tab == mTabs[0])
            {
                mViewPager.setCurrentItem(0);
            } else if (tab == mTabs[1])
            {
                mViewPager.setCurrentItem(1);
            } else if (tab == mTabs[2])
            {
                mViewPager.setCurrentItem(2);
            }

        }

        @Override
        public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onTabReselected(Tab tab, android.app.FragmentTransaction ft)
        {
            // TODO Auto-generated method stub

        }
    };

    public class MyPagerAdapter extends FragmentPagerAdapter
    {

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

        @Override
        public Fragment getItem(int position)
        {
            return MyFragment.create(addresses[position]);
        }

        @Override
        public int getCount()
        {
            return addresses.length;
        }
    }

    public static class MyFragment extends Fragment
    {
        public static MyFragment create(String address)
        {
            MyFragment f = new MyFragment();
            Bundle b = new Bundle();
            b.putString("address", address);
            f.setArguments(b);
            return f;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
        {
            Random r = new Random(System.currentTimeMillis());

            Bundle b = getArguments();

            View v = inflater.inflate(R.layout.fragment_viewpager1_layout1, null);
            v.setBackgroundColor(r.nextInt() >> 8 | 0xFF << 24);

            TextView txvAddress = (TextView) v.findViewById(R.id.textView1);
            txvAddress.setTextColor(r.nextInt() >> 8 | 0xFF << 24);
            txvAddress.setBackgroundColor(r.nextInt() >> 8 | 0xFF << 24);

            txvAddress.setText(b.getString("address", ""));
            return v;
        }

    }
}


布局:
复制代码 代码如下:

<?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/viewPager1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


3. 【推荐】第三种,使用 TabWidget + ViewPager 实现
该方法不错,推荐使用。

Activity:

复制代码 代码如下:

package com.swordy.demo.android.fragment;

import java.util.Random;

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.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TabWidget;
import android.widget.TextView;

import com.swordy.demo.android.R;

/**
 * 1. 使用TabWidget和ViewPager实现可滑动的Tab
 *
 * @author swordy
 * @email mryangjian@live.com
 * @since Jan 20, 2014
 * @version 1.0
 */
public class SlideTabs3 extends FragmentActivity
{
    private static final String TAG = "AndroidDemos.SlideTabs3";

    private ViewPager mViewPager;

    private PagerAdapter mPagerAdapter;

    private TabWidget mTabWidget;

    private String[] addresses = { "first", "second", "third" };

    private Button[] mBtnTabs = new Button[addresses.length];

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

        mTabWidget = (TabWidget) findViewById(R.id.tabWidget1);
        mTabWidget.setStripEnabled(false);
        mBtnTabs[0] = new Button(this);
        mBtnTabs[0].setFocusable(true);
        mBtnTabs[0].setText(addresses[0]);
        mBtnTabs[0].setTextColor(getResources().getColorStateList(R.color.button_bg_color_selector));
        mTabWidget.addView(mBtnTabs[0]);
        /*
         * Listener必须在mTabWidget.addView()之后再加入,用于覆盖默认的Listener,
         * mTabWidget.addView()中默认的Listener没有NullPointer检测。
         */
        mBtnTabs[0].setOnClickListener(mTabClickListener);

        mBtnTabs[1] = new Button(this);
        mBtnTabs[1].setFocusable(true);
        mBtnTabs[1].setText(addresses[1]);
        mBtnTabs[1].setTextColor(getResources().getColorStateList(R.color.button_bg_color_selector));
        mTabWidget.addView(mBtnTabs[1]);
        mBtnTabs[1].setOnClickListener(mTabClickListener);

        mBtnTabs[2] = new Button(this);
        mBtnTabs[2].setFocusable(true);
        mBtnTabs[2].setText(addresses[2]);
        mBtnTabs[2].setTextColor(getResources().getColorStateList(R.color.button_bg_color_selector));
        mTabWidget.addView(mBtnTabs[2]);
        mBtnTabs[2].setOnClickListener(mTabClickListener);

        mViewPager = (ViewPager) findViewById(R.id.viewPager1);
        mPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setOnPageChangeListener(mPageChangeListener);

        mTabWidget.setCurrentTab(0);
    }

    private OnClickListener mTabClickListener = new OnClickListener() {

        @Override
        public void onClick(View v)
        {
            if (v == mBtnTabs[0])
            {
                mViewPager.setCurrentItem(0);
            } else if (v == mBtnTabs[1])
            {
                mViewPager.setCurrentItem(1);

            } else if (v == mBtnTabs[2])
            {
                mViewPager.setCurrentItem(2);

            }
        }
    };

    private OnPageChangeListener mPageChangeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int arg0)
        {
            mTabWidget.setCurrentTab(arg0);
        }

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

        }

        @Override
        public void onPageScrollStateChanged(int arg0)
        {

        }
    };

    private class MyPagerAdapter extends FragmentStatePagerAdapter
    {

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

        @Override
        public Fragment getItem(int position)
        {
            return MyFragment.create(addresses[position]);
        }

        @Override
        public int getCount()
        {
            return addresses.length;
        }

    }

    public static class MyFragment extends Fragment
    {
        public static MyFragment create(String address)
        {
            MyFragment f = new MyFragment();
            Bundle b = new Bundle();
            b.putString("address", address);
            f.setArguments(b);
            return f;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState)
        {
            Random r = new Random(System.currentTimeMillis());

            Bundle b = getArguments();

            View v = inflater.inflate(R.layout.fragment_viewpager1_layout1, null);
            v.setBackgroundColor(r.nextInt() >> 8 | 0xFF << 24);

            TextView txvAddress = (TextView) v.findViewById(R.id.textView1);
            txvAddress.setTextColor(r.nextInt() >> 8 | 0xFF << 24);
            txvAddress.setBackgroundColor(r.nextInt() >> 8 | 0xFF << 24);

            txvAddress.setText(b.getString("address", ""));
            return v;
        }

    }
}

布局:

复制代码 代码如下:

<?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" >

    <TabWidget
        android:id="@+id/tabWidget1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right|center_vertical" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

这篇关于Android中实现可滑动的Tab的3种方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!