TabLayout的各种用法
来源:互联网 发布:金融软件供应商 编辑:程序博客网 时间:2024/06/06 01:18
- 布局
<android.support.design.widget.TabLayout android:id="@+id/tab_notice" android:layout_width="313dp" app:tabGravity="fill" android:layout_gravity="center" app:paddingStart="0dp" app:tabTextColor="#FD6363" app:tabContentStart="0dp" app:tabSelectedTextColor="#FFFFFF" app:tabBackground="@drawable/tab_background_selected" android:layout_height="33dp"/
- 如果添加边框
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"><solid android:color="@color/tab_background"/><stroke android:width="1dp" android:color="#FD6363"/></shape>
- fragment或activity中的使用
private void initTab() { list_fragment = new ArrayList<>(); CommentFragment commentFragment = new CommentFragment(); LikeFragment likeFragment = new LikeFragment(); FansFragment fansFragment = new FansFragment(); MeFragment meFragment = new MeFragment(); list_fragment.add(commentFragment); list_fragment.add(meFragment); list_fragment.add(fansFragment); list_fragment.add(likeFragment); list_table = new ArrayList<>(); list_table.add("评论"); list_table.add("@我"); list_table.add("粉丝"); list_table.add("点赞");mTabNotice.setTabMode(TabLayout.MODE_FIXED);mTabNotice.addTab(mTabNotice.newTab().setText(list_table.get(0)));mTabNotice.addTab(mTabNotice.newTab().setText(list_table.get(1)));mTabNotice.addTab(mTabNotice.newTab().setText(list_table.get(2)));mTabNotice.addTab(mTabNotice.newTab().setText(list_table.get(3)));adapter = new Find_tab_Adapter(getContext(),getChildFragmentManager(),list_fragment, list_table);mNoticeVp.setAdapter(adapter);mTabNotice.setupWithViewPager(mNoticeVp);}
- 添加分割线
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = View.inflate(getContext(), R.layout.fragment_notice, null); unbinder = ButterKnife.bind(this, mView); /** * 给tablayout设置分割线 */ LinearLayout linearLayout = (LinearLayout) mTabNotice.getChildAt(0); linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE); linearLayout.setDividerDrawable(ContextCompat.getDrawable(getContext(), R.drawable.layout_divider_vertical)); initTab(); mNoticeVp.setNoScroll(true); mNoticeVp.setOffscreenPageLimit(4); return mView;}
- 自定义的分割线
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"><solid android:color="@color/colorPrimaryDark"/> <size android:width="1dp" android:height="52dp" /></shape>
- ViewPager的Adapter
public class Find_tab_Adapter extends FragmentPagerAdapter { private List<BaseFragment> mBaseFragmentList; private List<String> tablist; private Context mContext; public Find_tab_Adapter(Context context,FragmentManager fm, List<BaseFragment> fragmentList, List<String> tablist) { super(fm); this.mContext =context; this.mBaseFragmentList = fragmentList; this.tablist = tablist; } @Override public Fragment getItem(int position) { return mBaseFragmentList.get(position); } @Override public int getCount() { return tablist.size(); } @Override public CharSequence getPageTitle(int position) { return tablist.get(position % tablist.size()); }}
- 如果要禁止滑动,需要自定义viewpager
public class NoScrollViewPager extends ViewPager { private boolean noScroll = false; public NoScrollViewPager(Context context, AttributeSet attrs) { super(context, attrs); } public NoScrollViewPager(Context context) { super(context); }public void setNoScroll(boolean noScroll) { this.noScroll = noScroll;}@Overridepublic void scrollTo(int x, int y) { super.scrollTo(x, y); }@Overridepublic boolean onTouchEvent(MotionEvent arg0) { if (noScroll) return false; else return super.onTouchEvent(arg0);@Overridepublic boolean onInterceptTouchEvent(MotionEvent arg0) { if (noScroll) return false; else return super.onInterceptTouchEvent(arg0); }@Overridepublic void setCurrentItem(int item, boolean smoothScroll) { super.setCurrentItem(item, smoothScroll); }@Overridepublic void setCurrentItem(int item) { super.setCurrentItem(item, false);//表示切换的时候,不需要切换时间。 }}
- 布局文件中引用
然后在fragment或者activity中的使用 mNoticeVp.setNoScroll(true);
- 2,给tablayout设置两行标题(类似于京东的限时抢购)
基本思路,需要自定义
private void setTabLayout() { initEvent(); mSecondViewpager.setOffscreenPageLimit(5); list_fragment = new ArrayList<>(); FirstFragment firstFragment = FirstFragment.newInstance(); SecondFragment secondFragment = SecondFragment.newInstance(); ThridFragment thridFragment = ThridFragment.newInstance(); FourFragment fourFragment = FourFragment.newInstance(); FiveFragment fiveFragment = FiveFragment.newInstance(); list_fragment.add(firstFragment); list_fragment.add(secondFragment); list_fragment.add(thridFragment); list_fragment.add(fourFragment); list_fragment.add(fiveFragment); list_table = new ArrayList<>(); list_table.add("08:00"); list_table.add("09:00"); list_table.add("10:00"); list_table.add("11:00"); list_table.add("12:00"); bottom_list = new ArrayList<>(); bottom_list.add("已开抢"); bottom_list.add("已开抢"); bottom_list.add("抢购中"); bottom_list.add("即将开始"); bottom_list.add("即将开始");// mSecondTab.addTab(mSecondTab.newTab().setText(list_table.get(0)));// mSecondTab.addTab(mSecondTab.newTab().setText(list_table.get(1)));// mSecondTab.addTab(mSecondTab.newTab().setText(list_table.get(2)));// mSecondTab.addTab(mSecondTab.newTab().setText(list_table.get(3)));// mSecondTab.addTab(mSecondTab.newTab().setText(list_table.get(4))); mSecondTab.setTabMode(TabLayout.MODE_FIXED); mSecondTab.setSelectedTabIndicatorHeight(0); adapter = new ViewPagerAdapterV2(this, getSupportFragmentManager(), list_fragment, list_table, bottom_list); mSecondViewpager.setAdapter(adapter); mSecondTab.setupWithViewPager(mSecondViewpager); for (int i = 0; i < mSecondTab.getTabCount(); i++) { TabLayout.Tab tab = mSecondTab.getTabAt(i); if (tab != null) { /** * 调用adapter中的gettabview */ tab.setCustomView(adapter.getTabView(i)); if (tab.getCustomView() != null) { View tabView = (View) tab.getCustomView().getParent(); tabView.setTag(i); } } } mSecondViewpager.setCurrentItem(1); mSecondViewpager.setCurrentItem(0); }private void initEvent() { mSecondTab.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { changeTabSelect(tab); } @Override public void onTabUnselected(TabLayout.Tab tab) { changeTabNormal(tab); } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }private void changeTabSelect(TabLayout.Tab tab) { View view = tab.getCustomView(); TextView txt_title = (TextView) view.findViewById(R.id.title_tv); txt_title.setTextColor(this.getResources().getColor(R.color.deep_main_color)); TextView txt_bottom = (TextView) view.findViewById(R.id.bottom_tv); txt_bottom.setTextColor(this.getResources().getColor(R.color.deep_main_color));// if (txt_bottom.getText().toString().equals("")) {// mSecondViewpager.setCurrentItem(0);// } else if (txt_title.getText().toString().equals("销量")) {// mSecondViewpager.setCurrentItem(1);// } else if (txt_title.getText().toString().equals("价格")){// mSecondViewpager.setCurrentItem(2);// }else if (txt_title.getText().toString().equals("筛选")){// mSecondViewpager.setCurrentItem(3);// } } private void changeTabNormal(TabLayout.Tab tab) { View view = tab.getCustomView(); TextView txt_title = (TextView) view.findViewById(R.id.title_tv); txt_title.setTextColor(Color.BLACK); TextView txt_bottom = (TextView) view.findViewById(R.id.bottom_tv); txt_bottom.setTextColor(Color.BLACK);// if (txt_title.getText().toString().equals("价格")) {// } else if (txt_title.getText().toString().equals("筛选")) {// } else {// } }
- ViewpagerAdapter
public class ViewPagerAdapterV2 extends FragmentPagerAdapter { private List<BaseFragment> mBaseFragmentList; private List<String> tablist; private List<String> bottomlist; private Context mContext; private int[] imageResId = { 0,0, R.drawable.search_icon_price_normal, R.mipmap.cate_filter };public ViewPagerAdapterV2(Context context, FragmentManager fm, List<BaseFragment> fragmentList, List<String> tablist,List<String> bottomlist) { super(fm); this.mContext =context; this.mBaseFragmentList = fragmentList; this.tablist = tablist; this.bottomlist=bottomlist; }@Overridepublic Fragment getItem(int position) { return mBaseFragmentList.get(position); }@Overridepublic int getCount() { return mBaseFragmentList.size();}@Overridepublic CharSequence getPageTitle(int position) { return tablist.get(position % tablist.size());}public View getTabView(int position){ View view = LayoutInflater.from(mContext).inflate(R.layout.viewpager_custom_v2, null); TextView txt_title = (TextView) view.findViewById(R.id.title_tv); txt_title.setText(tablist.get(position)); TextView txt_bottom = (TextView) view.findViewById(R.id.bottom_tv); txt_bottom.setText(bottomlist.get(position)); if (position == 0) { txt_title.setTextColor(mContext.getResources().getColo(R.color.deep_main_color)); txt_bottom.setTextColor(mContext.getResources().getCol(R.color.deep_main_color)); } else { txt_title.setTextColor(Color.BLACK); txt_bottom.setTextColor(Color.BLACK); } return view; }}
- R.layout.viewpager_custom_v2 的布局
<?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="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/title_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="@dimen/x18" android:text="11111111" android:gravity="center_horizontal" android:layout_gravity="center_horizontal" android:textColor="#444444" android:textSize="15sp" /> <TextView android:id="@+id/bottom_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/title_tv" android:layout_marginTop="@dimen/x9" android:text="11111111" android:gravity="center_horizontal" android:layout_gravity="center_horizontal" android:textColor="#444444" android:textSize="9sp" /></LinearLayout>
- 3,给tablayout添加icon和点击事件
private int[] imageResId = { 0,0, R.drawable.search_icon_price_normal, R.mipmap.cate_filter, };private void initTab() { list_fragment = new ArrayList<>(); ComprehensiveFragment comprehensiveFragment = ComprehensiveFragment.newInstance(mExittext); SaleNumberFragment saleNumberFragment = SaleNumberFragment.newInstance(mExittext); PriceFragment priceFragment = PriceFragment.newInstance(mExittext); FilterFragment filterFragment = FilterFragment.newInstance(mExittext); list_fragment.add(comprehensiveFragment); list_fragment.add(saleNumberFragment); list_fragment.add(priceFragment); list_fragment.add(filterFragment); list_table = new ArrayList<>(); list_table.add("综合"); list_table.add("销量"); list_table.add("价格"); list_table.add("筛选"); topicTabLayout.setTabMode(TabLayout.MODE_FIXED); //topicTabLayout.setTabGravity(View.TEXT_ALIGNMENT_CENTER); topicTabLayout.setSelectedTabIndicatorHeight(0); adapter = new ViewPagerAdapter(this, getSupportFragmentManager(), list_fragment,list_table); mVpTopic.setAdapter(adapter); topicTabLayout.setupWithViewPager(mVpTopic); /** * 调用本方法中的gettabview */ //setupTabIcons(); for (int i = 0; i < topicTabLayout.getTabCount(); i++) { TabLayout.Tab tab = topicTabLayout.getTabAt(i); if (tab != null) { /** * 调用adapter中的gettabview */ tab.setCustomView(adapter.getTabView(i)); if (tab.getCustomView() != null) { View tabView = (View) tab.getCustomView().getParent(); tabView.setTag(i); tabView.setOnClickListener(mTabOnClickListener); } } } mVpTopic.setCurrentItem(1); mVpTopic.setCurrentItem(0); /** * 用来设置indicator的长短 */ //topicTabLayout.post(new Runnable() {// @Override// public void run() {// SetIndicator.setIndicator(topicTabLayout, 33, 29);// }// });}private View.OnClickListener mTabOnClickListener = new View.OnClickListener() { @Override public void onClick(View view) { int pos = (int) view.getTag(); if (pos == 2) { TabLayout.Tab tab = topicTabLayout.getTabAt(pos); /** * 设置升序和降序的数据 */ setImage(tab); } else { TabLayout.Tab tab = topicTabLayout.getTabAt(pos); if (tab != null) { tab.select(); } } } };private void setupTabIcons() { topicTabLayout.getTabAt(0).setCustomView(getTabView(0)); topicTabLayout.getTabAt(1).setCustomView(getTabView(1)); topicTabLayout.getTabAt(2).setCustomView(getTabView(2)); topicTabLayout.getTabAt(3).setCustomView(getTabView(3)); }private void setImage(TabLayout.Tab tab) { switch (priceSortMode) { /** 从低到高的排序 */ case 0: priceSortMode = 1; break; /** 当mode为1说明其已被选中,那么选择2,及从高到低 */ case 1: priceSortMode = 2; break; /** 当mode为2说明其处于从高到低,那么选择1,从低到高 */ case 2: priceSortMode = 1; break; } setPriceSortDrawable(priceSortMode,tab);; }private void setPriceSortDrawable(int priceSortMode,TabLayout.Tab tab) { View view = tab.getCustomView(); ImageView img_title = (ImageView) view.findViewById(R.id.title_iv); switch (priceSortMode){ case 0: img_title.setImageResource(R.drawable.search_icon_price_normal); break; case 1: img_title.setImageResource(R.drawable.search_icon_price_down); break; case 2: img_title.setImageResource(R.drawable.search_icon_price_up); break; } }private void initEvent() { topicTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { changeTabSelect(tab); } @Override public void onTabUnselected(TabLayout.Tab tab) { changeTabNormal(tab); } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }private void changeTabSelect(TabLayout.Tab tab) { View view = tab.getCustomView(); ImageView img_title = (ImageView) view.findViewById(R.id.title_iv); TextView txt_title = (TextView) view.findViewById(R.id.title_tv); txt_title.setTextColor(this.getResources().getColor(R.color.deep_main_color)); if (txt_title.getText().toString().equals("综合")) { //img_title.setImageResource(R.drawable.tab_home_passed); mVpTopic.setCurrentItem(0); } else if (txt_title.getText().toString().equals("销量")) { //img_title.setImageResource(R.drawable.tab_mine_passed); mVpTopic.setCurrentItem(1); } else if (txt_title.getText().toString().equals("价格")){ //img_title.setImageResource(R.drawable.tab_info_passed); mVpTopic.setCurrentItem(2); }else if (txt_title.getText().toString().equals("筛选")){ //img_title.setImageResource(R.drawable.tab_info_passed); mVpTopic.setCurrentItem(3); } }private void changeTabNormal(TabLayout.Tab tab) { View view = tab.getCustomView(); ImageView img_title = (ImageView) view.findViewById(R.id.title_iv); TextView txt_title = (TextView) view.findViewById(R.id.title_tv); txt_title.setTextColor(Color.BLACK); if (txt_title.getText().toString().equals("价格")) { //img_title.setImageResource(R.drawable.tab_home_normal); } else if (txt_title.getText().toString().equals("筛选")) { // img_title.setImageResource(R.drawable.tab_mine_normal); } else { //img_title.setImageResource(R.drawable.tab_info_normal); } }public View getTabView(int position) { View view = LayoutInflater.from(this).inflate(R.layout.custom_tabtitle, null); TextView txt_title = (TextView) view.findViewById(R.id.title_tv); txt_title.setText(list_table.get(position)); ImageView img_title = (ImageView) view.findViewById(R.id.title_iv); img_title.setImageResource(imageResId[position]); if (position == 0) { txt_title.setTextColor(this.getResources().getColor(R.color.deep_main_color)); img_title.setImageResource(imageResId[position]); } else { txt_title.setTextColor(Color.BLACK); img_title.setImageResource(imageResId[position]); } return view; }
- ViewpagerAdapter
public class ViewPagerAdapter extends FragmentPagerAdapter { private List<BaseFragment> mBaseFragmentList; private List<String> tablist; private Context mContext; private int[] imageResId = { 0,0, R.drawable.search_icon_price_normal, R.mipmap.cate_filter };public ViewPagerAdapter(Context context, FragmentManager fm, List<BaseFragment> fragmentList, List<String> tablist) { super(fm); this.mContext =context; this.mBaseFragmentList = fragmentList; this.tablist = tablist; }@Overridepublic Fragment getItem(int position) { return mBaseFragmentList.get(position); }@Overridepublic int getCount() { return mBaseFragmentList.size(); }@Overridepublic CharSequence getPageTitle(int position) { return tablist.get(position % tablist.size());}public View getTabView(int position){ View view = LayoutInflater.from(mContext).inflate(R.layout.custom_tabtitle, null); TextView txt_title = (TextView) view.findViewById(R.id.title_tv); txt_title.setText(tablist.get(position)); ImageView img_title = (ImageView) view.findViewById(R.id.title_iv); img_title.setImageResource(imageResId[position]); if (position == 0) { txt_title.setTextColor(mContext.getResources().getColor(R.color.deep_main_color)); img_title.setImageResource(imageResId[position]); } else { txt_title.setTextColor(Color.BLACK); img_title.setImageResource(imageResId[position]); } return view; }}
- R.layout.custom_tabtitle的布局
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/title_tv" android:text="11111111" android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true"/> <ImageView android:id="@+id/title_iv" android:src="@drawable/search_icon_price_normal" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="3dp" android:layout_toRightOf="@id/title_tv"/></RelativeLayout>
- 4利用反射的原理来自定义indicator的长度
public class SetIndicator { public static void setIndicator(Context context, TabLayout tabs, int leftDip, int rightDip) { Class<?> tabLayout = tabs.getClass(); Field tabStrip = null; try { tabStrip = tabLayout.getDeclaredField("mTabStrip"); } catch (NoSuchFieldException e) { e.printStackTrace(); } tabStrip.setAccessible(true); LinearLayout ll_tab = null; try { ll_tab = (LinearLayout) tabStrip.get(tabs); } catch (IllegalAccessException e) { e.printStackTrace(); } int left = (int) (getDisplayMetrics(context).density * leftDip); int right = (int) (getDisplayMetrics(context).density * rightDip); for (int i = 0; i < ll_tab.getChildCount(); i++) { View child = ll_tab.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(); } }public static DisplayMetrics getDisplayMetrics(Context context) { DisplayMetrics metric = new DisplayMetrics(); ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric); return metric; }public static float getPXfromDP(float value, Context context) { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, context.getResources().getDisplayMetrics()); }public static 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(); } 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(); } }}
- 在fragment中的使用
topicTabLayout.post(new Runnable() { @Override public void run() { SetIndicator.setIndicator(topicTabLayout,33,29); } });
其中 33,29分别是距离左边和右边的距离
阅读全文
1 0
- TabLayout的各种用法
- Android:TabLayout的用法
- TabLayout的简单用法
- TabLayout的用法
- TabLayout的用法
- Android--TabLayout的用法
- TabLayout的用法
- TabLayout的用法
- 各种tabLayout
- materialdesign之tablayout的用法
- 浅析 - TabLayout的基本用法
- Android TabLayout的简单用法
- 关于TabLayout+ViewPager的用法
- TabLayout的一些特殊用法
- tablayout用法
- 最详细的 TabLayout 的用法
- 最详细的 TabLayout 的用法
- android design库之TabLayout的用法
- 调用自己封装的库,实现位图的格式转换
- Android布局加载React Native视图
- 宏定义 命名规范和常用的
- 根据滑动改变view的大小和位置
- Ubuntu 安装常用工具
- TabLayout的各种用法
- protobuf入门教程(六):导入定义(import)
- 深入浅出,带你撸出一个ButterKnife
- 搜集有意义的东西
- 团队协作及scrum sprint story编写
- lvs与nginx区别
- 画圆拖动0630
- How can I convert printStackTrace message to a string?
- 怎样将discuz所有页面的Powered by Discuz!去掉