此文转载自http://www.jianshu.com/p/a2263ee3e7c3

前几天学习了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" >
文/Hi_陈利健(简书作者)

原文链接:http://www.jianshu.com/p/a2263ee3e7c3

著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。

开源控件ViewPagerIndicator的使用的更多相关文章

  1. 开源控件ViewPagerIndicator学习

    导航条指示器.ViewPagerIndicator 地址 https://github.com/JakeWharton/ViewPagerIndicator Style是重用控件的一种技术.类似CSS ...

  2. Win10 UWP开发系列——开源控件库:UWPCommunityToolkit

    在开发应用的过程中,不可避免的会使用第三方类库.之前用过一个WinRTXamlToolkit.UWP,现在微软官方发布了一个新的开源控件库—— UWPCommunityToolkit 项目代码托管在G ...

  3. visual studio 2015引入开源控件DockPanel(最简单的方法)

    一.DockPanel简介 DockPanel是一个开源控件,能够实现子窗口的浮动,在官方给的demo有演示,在vs2017微软已经集成进入常用控件中.我主要使用的是多窗口浮动,和tabControl ...

  4. 开源整理:Android App新手指引开源控件

    开源整理:Android App新手指引开源控件 一个App第一次与用户接触或者发生大版本更新时,常常会用户进行新手引导,而一个好的新手指引,往往能够方便新用户快速了解操作你的应用功能.新手指引的重要 ...

  5. 转载: 开源整理:Android App新手指引开源控件

    http://blog.coderclock.com/2017/05/22/android/open-source-android-app-guide-view-library/ 开源整理:Andro ...

  6. 我的第一个开源控件-DragGridView

    我的第一个开源控件出炉了,希望各个小伙伴给个star,支持下.项目地址 1. 前言 因为项目须要,要做一个相似腾讯视频.频道管理.拖拽排序的效果.这个控件是在原地址 之上改造出来的.先看下效果图. 1 ...

  7. .Net 开源控件 NPlot使用小结

    NPlot是一款非常难得的.Net平台下的图表控件,能做各种曲线图,柱状图,饼图,散点图,股票图等,而且它免费又开源,使用起来也非常符合程序员的习惯.授权方式为BSD许可证. 下载链接: http:/ ...

  8. FMX开源控件

    FMX开源控件 这是群友谢顿做的控件,必须赞一个! https://github.com/zhaoyipeng/FMXComponents 这是loki的: https://sourceforge.n ...

  9. [原创][开源]SunnyUI.Net, C# .Net WinForm开源控件库、工具类库、扩展类库、多页面开发框架

    SunnyUI.Net, 基于 C# .Net WinForm 开源控件库.工具类库.扩展类库.多页面开发框架 Blog: https://www.cnblogs.com/yhuse Gitee: h ...

随机推荐

  1. 十大面试难题解惑,看完秒杀一切 HR 面。程序员必读!

    最能体现求职者能力的就是面试,能不能拿到Offer,取决于你面试时的表现,只有有准备才能在面试过程中游刃有余. 小编收集了10个面试官最爱提的问题,虽然题目千变万化,但是万变不离其宗,只要掌握了答题的 ...

  2. [USACO 12DEC]Running Away From the Barn

    Description It's milking time at Farmer John's farm, but the cows have all run away! Farmer John nee ...

  3. [HNOI2012]排队

    题目描述 某中学有 n 名男同学,m 名女同学和两名老师要排队参加体检.他们排成一条直线,并且任意两名女同学不能相邻,两名老师也不能相邻,那么一共有多少种排法呢?(注意:任意两个人都是不同的) 输入输 ...

  4. ●Joyoi Easy

    题链: http://www.joyoi.cn/problem/tyvj-1952题解: 概率dp (先做的BZOJ 4318: OSU![本人题解],然后就感觉这个题很简单了) 令p[i]表示第i个 ...

  5. 51nod 1514 美妙的序列

    Description 长度为n的排列,且满足从中间任意位置划分为两个非空数列后,左边的最大值>右边的最小值.问这样的排列有多少个%998244353 题面 Solution 正难则反 \(f[ ...

  6. bzoj 2118: 墨墨的等式

    Description 墨墨突然对等式很感兴趣,他正在研究a1x1+a2y2+-+anxn=B存在非负整数解的条件,他要求你编写一个程序,给定N.{an}.以及B的取值范围,求出有多少B可以使等式存在 ...

  7. 51nod 1770 数数字

    1770 数数字 基准时间限制:1 秒 空间限制:262144 KB 分值: 20 难度:3级算法题  收藏  关注 统计一下 aaa ⋯ aaan个a × b 的结果里面 ...

  8. Git常用命令及常见问题解决

    $ mkdir xxx       ----创建xxx目录 $ cd learngit     ----切到xxx目录下 $ pwd               ----查看当前文件所在目录 $ gi ...

  9. Linux下解决无法远程连接数据库问题

    起因 今天在ubuntu16.04环境下通过mysql workbench访问远程数据库时,发现无法连接问题,解决思路及方法记录如下,不足之处,请多指教. 问题 通过workbench输入密码访问时报 ...

  10. 美团java后台实习三面

    美团一面(50分钟) 1.spring的理解. 1.项目相关 2.Redis缓存的应用 3.http解析的全过程 4.Java中的锁 5.Hashmap和concurrenthashMap源码 6.死 ...