众所周知Android的Tab控件不是很好用,因此Github上的PagerSlidingTabStrip项目被广为使用,该项目地址为:
https://github.com/astuetz/PagerSlidingTabStrip
其示例图如下:
由于其demo代码较长,难以理解,因此我总结了一个最简的使用方法。
第一,在ADT中导入PagerSlidingTabStrip中的library项目,若使用Android Studio则直接导入即可,若使用ADT则需参考我的上一篇文章进行导入:
http://blog.csdn.net/logicteamleader/article/details/45202863
并将library项目改名为PagerSlidingTabStrip-lib
第二,创建自己的项目,其中引用PagerSlidingTabStrip-lib项目。在自己的项目中创建几个Fragment,并继承FragmentPagerAdapter类实现一个MyPagerAdapter类,代码如下(略去了几个Fragment的layout和代码):
package wxbtabexam.apkkids.com; import java.util.ArrayList; 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.util.TypedValue; import com.astuetz.PagerSlidingTabStrip; import com.example.wxbtabexam.R; public class HomeActivity extends FragmentActivity { private ViewPager pager; private MyPagerAdapter pagerAdapter; private PagerSlidingTabStrip tabs; private int currentColor =0xFF5161BC; @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); setContentView(R.layout.home_layout); tabs = (PagerSlidingTabStrip) this.findViewById(R.id.tabs); pager = (ViewPager) this.findViewById(R.id.pager); ArrayList<Fragment> fragmentlist = new ArrayList<Fragment>(); //注意,这三个Fragment需要自己实现 ButtonFragment buttonFragment = new ButtonFragment(); TextFragment textFragment = new TextFragment(); MyListFragment mylistFragment = new MyListFragment(); fragmentlist.add(buttonFragment); fragmentlist.add(textFragment); fragmentlist.add(mylistFragment); pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragmentlist); pager.setAdapter(pagerAdapter); final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources() .getDisplayMetrics()); pager.setPageMargin(pageMargin); tabs.setViewPager(pager); changeColor(currentColor); } private void changeColor(int newColor) { tabs.setIndicatorColor(newColor); currentColor = newColor; } //MyPagerAdapter要和上面实现的三个Fragment对应起来 class MyPagerAdapter extends FragmentPagerAdapter{ private final String[] TITLES = { "Buttons", "TextViews", "List" }; private ArrayList<Fragment> fragmentlist; public MyPagerAdapter(FragmentManager fm,ArrayList<Fragment> list) { super(fm); fragmentlist = list; } @Override public CharSequence getPageTitle(int position) { return TITLES[position]; } @Override public int getCount() { return fragmentlist.size(); } public Fragment getItem(int position) { return fragmentlist.get(position); } } }
全新android Tab控件PagerSlidingTabStrip最简使用方法
原文地址:http://blog.csdn.net/logicteamleader/article/details/45487263