android 顶部导航栏
效果图如上:
实现这个效果采用TabLayout和ViewPager的两者结合使用;
首先在build.griadle添加依赖库:compile 'com.android.support:design:25.3.1';
布局文件:
<android.support.design.widget.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
在activity中进行编写:
init();
mTab = new String[]{"好友","群","多人聊天","设备"};
mListTitle = new ArrayList<>();
mListTitle.add(new FriendFragment());
mListTitle.add(new GroupFragment());
mListTitle.add(new FriendsFragment());
mListTitle.add(new DeviceFragment());
TabAdapter tabAdapter = new TabAdapter(getSupportFragmentManager());
mViewPager.setAdapter(tabAdapter);
//绑定ViewPager
mTabLayout.setupWithViewPager(mViewPager);
// TabLength tabLength = new TabLength();
// //tabLength.setIndicator(mTabLayout,15,5);
private void init() {
mTabLayout = (TabLayout) findViewById(R.id.tablayout);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mTabLayout.post(new Runnable() {
@Override
public void run() {
setIndicator(mTabLayout,20,20);
}
});
}
public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
Class<?> tabLayout = tabs.getClass();
Field tabStrip = null;
try {
tabStrip = tabLayout.getDeclaredField("mTabStrip");
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
assert tabStrip != null;
tabStrip.setAccessible(true);
LinearLayout llTab = null;
try {
llTab = (LinearLayout) tabStrip.get(tabs);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
for (int i = 0; i < llTab.getChildCount(); i++) {
View child = llTab.getChildAt(i);
child.setPadding(0, 0, 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
params.leftMargin = left;
params.rightMargin = right;
child.setLayoutParams(params);
child.invalidate();
}
}
class TabAdapter extends FragmentPagerAdapter{
public TabAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return mListTitle.get(position);
}
@Override
public int getCount() {
return mListTitle.size();
}
//重写这个方法,将设置每个Tab的标题
@Override
public CharSequence getPageTitle(int position) {
return mTab[position];
}
}
这就可以实现效果图了。