开源控件ViewPagerIndicator的使用

前几天学习了ViewPager作为引导页和Tab的使用方法。后来也有根据不同的使用情况改用Fragment作为Tab的情况,以及ViewPager结合FragmentPagerAdapter的使用。今天学习一种利用开源控件ViewPagerIndicator实现Tab的方式,也是各种新闻客户端等APP开发最常用的。

在此感谢xiaanming老师分享的代码,以及JakeWharton大神为广大开发者提供的开源框架。


1.如何使用开源框架
第1步:improt library项目
第2步:导入library进我们自己新建的项目
从Github上Download下来这个zip包之后,里面会有一个library文件,是库工程,还有一个sample,是作者提供的例子(将sample这个项目import,可以看到作者提供的各种样式的Indicator,作为参考)。如果要在作者例子的基础上自己开发样式,需要将library项目import进Eclipse(library是库工程,我们需要将其作为我们自己项目的依赖库)。然后创建一个新项目,新建的项目libs目录下面有android-support-v4.jar,这个必须删除,因为ViewPageIndicator里面有这个库,我们项目中不允许两个android-support-v4.jar,不删除我们的项目是不能编译的。右键项目—Properties—Android选项卡—Add—选择library库工程—OK,导入完毕。


2.MainActivity布局
布局中仅一个ViewPager,一个ViewPagerIndicator.(本例使用的是其中一种ViewPagerIndicator:TabPagerIndicator)
注意它应该紧邻在ViewPager的上方或下方,总之要挨在一起。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.viewpagerindicator.TabPageIndicator
        android:id="@+id/indicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/base_action_bar_bg" >
    </com.viewpagerindicator.TabPageIndicator>

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </android.support.v4.view.ViewPager>

</LinearLayout>

3.MainActivity代码
第1步:实例化ViewPager,给ViewPager设置Adapter
第2步:实例化TabPageIndicator,TabPageIndicator与ViewPager绑在一起
第3步:在Indicator上设置OnPagerChangeListner监听器
第4步:定义Adapter(继承FragmentPagerAdapter)

先实例化ViewPager,然后实例化TabPageIndicator,然后设置TabPageIndicator和ViewPager关联,就是调用TabPageIndicator的setViewPager(ViewPager view)方法,这样子就实现了点击上面的Tab,下面的ViewPager切换;滑动ViewPager,上面的Tab跟着切换。
ViewPager的每一个Item我们使用的是Fragment,使用Fragment可以使布局更加灵活一点,建议多用Fragment。
设置监听的时候,需要用Indicator提供的OnPagerChangeListener方法

public class MainActivity extends FragmentActivity {  
    /** 
     * Tab标题 
     */  
    private static final String[] TITLE = new String[] { "头条", "房产", "另一面", "女人",  
                                                        "财经", "数码", "情感", "科技" };  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        //实例化ViewPager, 然后给ViewPager设置Adapter  
        ViewPager pager = (ViewPager)findViewById(R.id.pager);  
        FragmentPagerAdapter adapter = new TabPageIndicatorAdapter(getSupportFragmentManager());  
        pager.setAdapter(adapter);  
  
        //实例化TabPageIndicator,然后与ViewPager绑在一起(核心步骤)  
        TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator);  
        indicator.setViewPager(pager);  
          
        //如果要设置监听ViewPager中包含的Fragment的改变(滑动切换页面),使用OnPageChangeListener为它指定一个监听器,那么不能像之前那样直接设置在ViewPager上了,而要设置在Indicator上,
        indicator.setOnPageChangeListener(new OnPageChangeListener() {  
              
            @Override  
            public void onPageSelected(int arg0) {  
                Toast.makeText(getApplicationContext(), TITLE[arg0], Toast.LENGTH_SHORT).show();  
            }  
              
            @Override  
            public void onPageScrolled(int arg0, float arg1, int arg2) {  
                  
            }  
              
            @Override  
            public void onPageScrollStateChanged(int arg0) {  
                  
            }  
        });  
          
    }  
      
    /** 
     * 定义ViewPager的适配器 
     */  
    class TabPageIndicatorAdapter extends FragmentPagerAdapter {  
        public TabPageIndicatorAdapter(FragmentManager fm) {  
            super(fm);  
        }  
  
        @Override  
        public Fragment getItem(int position) {  
            //新建一个Fragment来展示ViewPager item的内容,并传递参数  
            Fragment fragment = new ItemFragment();    
            Bundle args = new Bundle();    
            args.putString("arg", TITLE[position]);    
            fragment.setArguments(args);    
              
            return fragment;  
        }  
  
        @Override  
        public CharSequence getPageTitle(int position) {  
            return TITLE[position % TITLE.length];  
        }  
  
        @Override  
        public int getCount() {  
            return TITLE.length;  
        }  
    }  
}  

4.定义ViewPager每一个Item的代码(每一个Fragment)
此例只定义了一个Fragment,R.layout.fragment仅定义了一个TextView。在这个Fragment代码中,通过Bundle传递一个Key-value数据,内容仅一个字符串。实际开发的时候,针对每个ViewPager的item,要设计每个不同的Fragment的布局、代码内容等。此例代码只做示范。

public class ItemFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        //动态找到布局文件,再从这个布局中find出TextView对象
        View contextView = inflater.inflate(R.layout.fragment_item, container, false);
        TextView mTextView = (TextView) contextView.findViewById(R.id.textview);

        //获取Activity传递过来的参数
        Bundle mBundle = getArguments();
        String title = mBundle.getString("arg");

        mTextView.setText(title);

        return contextView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }   
}

5.Indicator的样式修改
第1步:在values/styles中添加<style>:
本例中,添加了3个<style>,其中"StyledIndicators"是我们需要的<style>,它其中的<item>使用了"CustomTabPageIndicator"这个<style>,这个<style>其中的一个<item>又使用了"CustomTabPageIndicator.Text"这个<style>。
实际上可以把"StyledIndicators"<style>的<item>属性全部写死在"StyledIndicators"下面。 但这样层级分离式的写法,增强了代码的复用性,以便后期维护和功能代码增删操作。

    <style name="StyledIndicators" parent="@android:style/Theme.Light">
        <item name="vpiTabPageIndicatorStyle">@style/CustomTabPageIndicator</item>
    </style>

    <style name="CustomTabPageIndicator" parent="Widget.TabPageIndicator">
        <item name="android:background">@drawable/tab_indicator</item>
        <item name="android:textAppearance">@style/CustomTabPageIndicator.Text</item>
        <item name="android:textSize">14sp</item>
        <item name="android:dividerPadding">8dp</item>
        <item name="android:showDividers">middle</item>
        <item name="android:paddingLeft">10dp</item>
        <item name="android:paddingRight">10dp</item>
        <item name="android:fadingEdge">horizontal</item>
        <item name="android:fadingEdgeLength">8dp</item>
    </style>

    <style name="CustomTabPageIndicator.Text" parent="android:TextAppearance.Medium">
        <item name="android:typeface">monospace</item>
        <item name="android:textColor">@drawable/selector_tabtext</item>
    </style>

第2步:创建<style>中使用到的drawable资源文件:
在drawable目录下添加tab_indicator.xml 和selector_tabtext.xml。
本例中使用到了自定义的drawable资源,自定义drawable一般配合上面的自定义style使用,提供图片、颜色等资源来支持自定义样式:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="false" android:state_pressed="false" android:drawable="@android:color/transparent" />
    <item android:state_selected="false" android:state_pressed="true" android:drawable="@android:color/transparent" />     
    <item android:state_selected="true"  android:state_pressed="false" android:drawable="@drawable/base_tabpager_indicator_selected" />
    <item android:state_selected="true"  android:state_pressed="true" android:drawable="@drawable/base_tabpager_indicator_selected" />
</selector>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:color="#EE2C2C" />
    <item android:state_pressed="true" android:color="#EE2C2C" />
    <item android:state_focused="true" android:color="#EE2C2C" />
    <item android:color="@android:color/black"/>
</selector>

第3步:在Manifest中改用我们自定义的样式:
本例中直接在application上修改,也可以单独修改一个activity

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/StyledIndicators" >
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容