Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android資訊 >> Android可滑動Tab的3種實現方法

Android可滑動Tab的3種實現方法

編輯:Android資訊

Android系統中有著各種各樣的Tab組件,並且大部分也都支持滑動,本文將結合代碼來實現3種方式的Android可滑動Tab組件,有需要的Android開發者可以收藏。

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 [email protected]
 * @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 [email protected]
 * @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 [email protected]
 * @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>
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved