先来看看效果图
首先这是Material Design里的Tab空间实现的
参考资料
官方英文文档:
http://www.google.com/design/spec/material-design/
中文版网站:
http://wiki.jikexueyuan.com/project/material-design/
一个大神写的文档
http://www.jcodecraeer.com/a/anzhuokaifa/developer/2015/0531/2958.html?mType=Group
代码如下
1.LocalMusicActivity的xml布局:
其实就是在viewpager上面放一个TabLayout
<RelativeLayout 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" tools:context="com.example.archermind.musicplayer.activity.LocalMusicActivity">
<android.support.design.widget.TabLayout
android:id="@+id/tablelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"></android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_below="@id/tablelayout"
android:layout_height="match_parent"
/>
</RelativeLayout>
2.LocalActivity的java代码
public class LocalMusicActivity extends AppCompatActivity {
private ArrayList<String> listTitle;
private ArrayList<Fragment> listFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_local_music);
initList();
initView();
}
private void initList() {
listTitle = new ArrayList<String>();
listTitle.add("单曲");
listTitle.add("歌手");
listTitle.add("专辑");
listFragment = new ArrayList<Fragment>();
listFragment.add(new SingleFragment());
listFragment.add(new SingerFragment());
listFragment.add(new SpecailFragment());
}
private void initView() {
TabLayout tabnavigation = (TabLayout) findViewById(R.id.tablelayout);
ViewPager vpnavigation = (ViewPager) findViewById(R.id.viewpager);
NavigationAdapter adapter = new NavigationAdapter(getSupportFragmentManager(),listFragment,listTitle);
vpnavigation.setAdapter(adapter);
tabnavigation.setupWithViewPager(vpnavigation);
}
其中最主要的代码可参考下面的话
Design library的TabLayout 既实现了固定的选项卡 - view的宽度平均分配,也实现了可滚动的选项卡 - view宽度不固定同时可以横向滚动。选项卡可以在程序中动态添加:
TabLayout tabLayout = ...;
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
这里是重点
但是如果你使用ViewPager在tab之间横向切换,你可以直接从 PagerAdapter 的 getPageTitle() 中创建选项卡,然后使用setupWithViewPager()将两者联系在一起。它可以使tab的选中事件能更新ViewPager,同时ViewPager
的页面改变能更新tab的选中状态。
3.Adapter的java代码
public class NavigationAdapter extends FragmentPagerAdapter {
private List<Fragment> listFragment;
private List<String> listitle;
public NavigationAdapter(FragmentManager fm ,ArrayList<Fragment> listFragment,ArrayList<String> listitle) {
super(fm);
this.listFragment = listFragment;
this.listitle = listitle;
}
@Override
public CharSequence getPageTitle(int position) {
return listitle.get(position);
}
@Override
public Fragment getItem(int i) {
return listFragment.get(i);
}
@Override
public int getCount() {
return listFragment.size();
}
}