如图是效果图
开发中经常会用到上面是一个Tab下面是一个ViewPager(ViewPager再包含几个Fragment),当点击Tab或是滑动ViewPager,Tab及ViewPager都会发生对应的变化
如图我实现的上面一个Tab是自己定义的布局让其继承HorizontalScrollView,下面一个使用系统PagerTabStrip很简单,
当然引用别人的框架Android-ViewPagerIndicator(https://github.com/JakeWharton/ViewPagerIndicator)实现更简单
如下是主要代码
package com.it.hello.activity.assets; import java.util.ArrayList; import com.it.hello.R; import com.it.hello.activity.entity.ChannelItem; import com.it.hello.activity.fragment.FourFragment; import com.it.hello.activity.fragment.MThreeFragment; import com.it.hello.activity.fragment.OneFragment; import com.it.hello.activity.myfragment.MyFragmentOne; import com.it.hello.activity.myfragment.MyFragmentTwo; import com.it.hello.activity.util.DensityUtils; import com.it.hello.activity.widget.ColumnHorizontalScrollView; 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.FragmentStatePagerAdapter; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.ViewPager; import android.util.SparseArray; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.RelativeLayout.LayoutParams; /** * PagerTabStrip实现ViewPager的滑动 * @author zh * */ public class MyStripActivity extends FragmentActivity { private ViewPager mViewPager; private PagerTabStrip pager_tab_strip; /** 自定义的HorizontalScrollView */ private ColumnHorizontalScrollView mColumnHorizontalScrollView; private LinearLayout mRadioGroup_content; /** 用户选择的分类列表 */ private ArrayList<ChannelItem> userChannelItems = new ArrayList<ChannelItem>(); /** 当前选中的栏目 */ private int columnSelectIndex = 0; /** 屏幕的宽度 */ private int mScreeWidth = 0; /** Item宽度 */ private int mItemWidth = 0; private View view; @Override protected void onCreate(Bundle arg0) { // TODO Auto-generated method stub super.onCreate(arg0); setContentView(R.layout.activity_strip); mScreeWidth = DensityUtils.getWindowsWidth(this); mItemWidth = mScreeWidth / 3; // 一个Item宽度为屏幕的3分之一 mViewPager = (ViewPager) findViewById(R.id.vp); pager_tab_strip = (PagerTabStrip) findViewById(R.id.pager_tab_strip); // 设置标签下划线的颜色 mColumnHorizontalScrollView = (ColumnHorizontalScrollView) findViewById(R.id.mColumnHorizontal); mRadioGroup_content = (LinearLayout) findViewById(R.id.mRadioGroup); initColumData(); //取消Tab 下面的长横线 pager_tab_strip.setDrawFullUnderline(false); //改变Tab线的颜色 pager_tab_strip.setTabIndicatorColor(getResources().getColor( R.color.indecolor)); mViewPager.setOffscreenPageLimit(3); mViewPager.setAdapter(new MainAdapter(getSupportFragmentManager())); } private void initColumData() { // TODO Auto-generated method stub userChannelItems = new ArrayList<ChannelItem>(); ChannelItem item = new ChannelItem(0, "标签0", 0, 0); ChannelItem item1 = new ChannelItem(0, "标签1", 0, 0); ChannelItem item2 = new ChannelItem(0, "标签2", 0, 0); ChannelItem item3 = new ChannelItem(0, "标签3", 0, 0); ChannelItem item4 = new ChannelItem(0, "标签4", 0, 0); userChannelItems.add(item); userChannelItems.add(item1); userChannelItems.add(item2); userChannelItems.add(item3); userChannelItems.add(item4); initTabColumn(); /** * ViewPager切换监听的方法 */ mViewPager .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // TODO Auto-generated method stub mViewPager.setCurrentItem(position); selectTab(position); initColumData(); } }); } /** * 初始化TabColumn栏目项 */ private void initTabColumn() { // TODO Auto-generated method stub mRadioGroup_content.removeAllViews(); int count = userChannelItems.size(); mColumnHorizontalScrollView.setParam(this, mScreeWidth, mRadioGroup_content); for (int i = 0; i < count; i++) { RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( mItemWidth, LayoutParams.WRAP_CONTENT); params.leftMargin = 5; params.rightMargin = 5; view = View.inflate(this, R.layout.item_mytab, null); TextView tv = (TextView) view.findViewById(R.id.tab_title); View line = (View) view.findViewById(R.id.tab_line); tv.setId(i); tv.setText(userChannelItems.get(i).getName()); if (columnSelectIndex == i) { tv.setSelected(true); line.setSelected(true); } view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) { View localView = mRadioGroup_content.getChildAt(i); if (localView != arg0) { localView.setSelected(false); } else { localView.setSelected(true); mViewPager.setCurrentItem(i); } } } }); mRadioGroup_content.addView(view, i, params); } } /** * 选择的Column里面的Tab * */ private void selectTab(int tab_postion) { columnSelectIndex = tab_postion; for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) { View checkView = mRadioGroup_content.getChildAt(tab_postion); int k = checkView.getMeasuredWidth(); int l = checkView.getLeft(); int i2 = l + k / 2 - mScreeWidth / 2; mColumnHorizontalScrollView.smoothScrollTo(i2, 0); } // 判断是否选中 for (int j = 0; j < mRadioGroup_content.getChildCount(); j++) { View checkView = mRadioGroup_content.getChildAt(j); boolean ischeck; if (j == tab_postion) { ischeck = true; } else { ischeck = false; } checkView.setSelected(ischeck); } } /** * ViewPager的适配器 * @author zh * */ private class MainAdapter extends FragmentStatePagerAdapter { public MainAdapter(FragmentManager fm) { super(fm); // TODO Auto-generated constructor stub } // 每个条目返回的Fragment @Override public Fragment getItem(int position) { // TODO Auto-generated method stub return createFragment(position); } // 一共多少个条目 @Override public int getCount() { // TODO Auto-generated method stub return 5; } // 返回每个条目的标题 @Override public CharSequence getPageTitle(int position) { return "标签" + position; } } //private static Map<Integer, Fragment> mFragmentMap = new HashMap<Integer, Fragment>(); private static SparseArray<Fragment> mFragmentMap = new SparseArray<Fragment>(); public Fragment createFragment(int position) { // TODO Auto-generated method stub Fragment fragment = null; fragment = mFragmentMap.get(position);//在集合中去除Fragment if(fragment == null){//如果没在集合中取出来 需要重新创建 if (position == 0) { fragment = new MyFragmentOne(); } else if (position == 1) { fragment = new MyFragmentTwo(); } else if (position == 3) { fragment = new MThreeFragment(); } else if (position == 4) { fragment = new FourFragment(); } else { fragment = new OneFragment(); } if(fragment != null){ mFragmentMap.put(position, fragment);//把创建好的Fragment存放到集合中缓存起来 } } return fragment; } }
布局代码
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.it.hello.activity.widget.ColumnHorizontalScrollView android:id="@+id/mColumnHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="none" > <LinearLayout android:id="@+id/mRadioGroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#333" android:gravity="center_vertical" android:orientation="horizontal" /> </com.it.hello.activity.widget.ColumnHorizontalScrollView> <android.support.v4.view.ViewPager android:id="@+id/vp" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v4.view.PagerTabStrip android:id="@+id/pager_tab_strip" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:background="#ffffff" android:paddingBottom="4dp" android:paddingTop="4dp" android:textColor="#000" /> </android.support.v4.view.ViewPager> </LinearLayout>
自定义的ColumnHorizontalScrollView
package com.it.hello.activity.widget; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.HorizontalScrollView; public class ColumnHorizontalScrollView extends HorizontalScrollView { /** 传入整体布局 */ private View ll_content; /** 传入拖动栏布 */ // private View rl_column; /** 屏幕宽度 */ private int mScreenWitdh = 0; /** 父类的活动activity */ private Activity activity; public ColumnHorizontalScrollView(Context context) { super(context); } public ColumnHorizontalScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public ColumnHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * 在拖动的时 * */ // @Override // protected void onScrollChanged(int paramInt1, int paramInt2, int // paramInt3, int paramInt4) { // super.onScrollChanged(paramInt1, paramInt2, paramInt3, paramInt4); // //shade_ShowOrHide(); // if(!activity.isFinishing() && ll_content !=null){ // }else{ // return; // } // if(paramInt1 ==0){ // return; // } // if(ll_content.getWidth() - paramInt1 + rl_column.getLeft() == // mScreenWitdh){ // return; // } // } /** * 传入父类布局中的资源文件 * */ public void setParam(Activity activity, int mScreenWitdh, View paramView1) { this.activity = activity; this.mScreenWitdh = mScreenWitdh; this.ll_content = paramView1; } /** * 判断左右阴影的显示隐藏效 * */ public void shade_ShowOrHide() { if (!activity.isFinishing() && ll_content != null) { measure(0, 0); // 如果整体宽度小于屏幕宽度的话,那左右阴影都隐藏 if (mScreenWitdh >= getMeasuredWidth()) { // leftImage.setVisibility(View.GONE); // rightImage.setVisibility(View.GONE); } } else { return; } // 如果滑动在最左边时,左边阴影隐藏,右边显示 if (getLeft() == 0) { // leftImage.setVisibility(View.GONE); // rightImage.setVisibility(View.VISIBLE); return; } // 如果滑动在最右边时,左边阴影显示,右边隐藏 if (getRight() == getMeasuredWidth() - mScreenWitdh) { // leftImage.setVisibility(View.VISIBLE); // rightImage.setVisibility(View.GONE); return; } // 否则,说明在中间位置,左、右阴影都显示 // leftImage.setVisibility(View.VISIBLE); // rightImage.setVisibility(View.VISIBLE); } }
/**获取屏幕的宽*/ public final static int getWindowsWidth(Activity activity) { DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); return dm.widthPixels; }
3.最近用TabLayout + ViewPager也可以实现效果 而且代码很简单
要先添加倚赖
compile 'com.android.support:design:25.3.1'
如下是所有代码 先看布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.TabLayout android:id="@+id/tablayout" android:layout_width="match_parent" android:layout_height="60dp" app:tabIndicatorColor="#49dd12" app:tabSelectedTextColor="#49dd12" app:tabTextColor="@android:color/darker_gray" /> <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
package com.item.jiejie.lite.tab; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TableLayout; import com.item.jiejie.lite.R; import java.util.ArrayList; import java.util.List; public class MyTabActivity extends AppCompatActivity { private ViewPager viewPager; private TabLayout tabLayout; private List<Fragment> fragments = new ArrayList<>(); private List<String> tabs = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_tab); initData(); } private void initData() { tabs.add("新消息"); tabs.add("朋友圈"); tabs.add("公众号"); fragments.add(new TabFrament(this,tabs.get(0))); fragments.add(new TabFrament(this,tabs.get(1))); fragments.add(new TabFrament(this,tabs.get(2))); tabLayout = (TabLayout) findViewById(R.id.tablayout); viewPager = (ViewPager)findViewById(R.id.viewpager); //设置TabLayout的模式 tabLayout.setTabMode(TabLayout.MODE_FIXED); viewPager.setAdapter(new TabAdapter(getSupportFragmentManager())); //关联ViewPager和TabLayout tabLayout.setupWithViewPager(viewPager); //设置分割线 LinearLayout linear = (LinearLayout)tabLayout.getChildAt(0); linear.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); linear.setDividerDrawable(ContextCompat.getDrawable(this,R.drawable.divider)); //设置分割线间隔 linear.setDividerPadding(dip2px(15)); } //像素单位转换 public int dip2px(int dip) { float density = getResources().getDisplayMetrics().density; return (int) (dip * density + 0.5); } class TabAdapter extends FragmentPagerAdapter{ public TabAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } //显示标签上的文字 @Override public CharSequence getPageTitle(int position) { return tabs.get(position); } } }
package com.item.jiejie.lite.tab; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Created by jiejie on 2017/5/3. */ public class TabFrament extends Fragment { private Context context; private String content; public TabFrament() { } public TabFrament(Context contexts, String content) { this.context = contexts; this.content = content; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { TextView textView = new TextView(context); textView.setText(content); textView.setTextSize(30); textView.setGravity(Gravity.CENTER); return textView; } }
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#80c0c0c0"/> <size android:width="1dp"/> </shape>