实现方式
实现的方式有很多种 这里总结最常见的几种方式,以后再添加其他的。
viewPager + RadioGroup
viewPager + FragmentTabHost
viewpager +TabLayout
viewPager+RadioGroup
感觉这是最简单的一个了,我也就不贴代码 说说我理解的思路吧
通过给pager 和RadioGroup 添加监听,监听两个控件的变化 实现联动
当viewPager的显示pager改变就会触发监听 ,在监听中选中对应的RadioButton即可
当RadioGroup发生 选中改变时也会触发监听 ,在选中改变后 设置显示对应的pager即可
FragmentTabHost +viewpager
这个方式 跟上面那个方式差不多 都是通过 监听 实现联动
如果只使用FragmentTabHost 只能实现 点击tab切换 页面的效果 不能实现左右滑动 而 结合viewPager 刚好实现这一效果
先来看看FragmentTabHost经常用的方法
- setup() 在使用addTab之前调用 设置必要的数据 如 FragmentManager,Fragment的容器id - addTab() 添加标签 - newTabSpec() 新建 tab - setCurrentTab() 设置当前显示的标签 - setOnChangeTabListtener 设置tab选中改变监听 - tabHost.getTabWidget().setDividerDrawable(null); //去除间隔线 - Tab的常用方法: - setIndicator() 可以设置view 和 字符串main布局<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/activity_tab_pager"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="com.skymxc.demo.fragment.TabPagerActivity"><android.support.v4.view.ViewPagerandroid:id="@+id/pager"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"></android.support.v4.view.ViewPager><android.support.v4.app.FragmentTabHostandroid:id="@+id/tab_host"android:layout_width="match_parent"android:layout_height="wrap_content"></android.support.v4.app.FragmentTabHost></LinearLayout>
Framgent 简单起见 就不写布局文件了 其他的Fragment 跟这个类似
public class DiscoverFragment extends Fragment {@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {TextView textView = new TextView(getActivity());textView.setText("发现");textView.setGravity(Gravity.CENTER);return textView;}}
tab 的布局 图片在上 文本在下 比较简单
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width="match_parent"android:layout_height="match_parent"><ImageViewandroid:id="@+id/icon"android:layout_width="30dp"android:layout_height="30dp"android:layout_gravity="center"/><TextViewandroid:id="@+id/title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@color/selector_font"android:text="发现"android:layout_gravity="center"/></LinearLayout>
selector 基本类似 这里贴一个
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:state_selected="true" android:drawable="@mipmap/cb_icon_discover_selected"/><item android:drawable="@mipmap/cb_icon_discover_normal"/></selector>
java 代码
初始化 TabHost
private void initTabHost() {tabHost.setup(this,getSupportFragmentManager(), R.id.pager);tabHost.getTabWidget().setDividerDrawable(null);tabHost.addTab(tabHost.newTabSpec("discover").setIndicator(createView(R.drawable.selector_bg,"发现")), DiscoverFragment.class,null);tabHost.addTab(tabHost.newTabSpec("attach").setIndicator(createView(R.drawable.selector_bg_attach,"关注")), AttachFragment.class,null);tabHost.addTab(tabHost.newTabSpec("message").setIndicator(createView(R.drawable.selector_bg_message,"消息")), MsgFragment.class,null);tabHost.addTab(tabHost.newTabSpec("info").setIndicator(createView(R.drawable.selector_bg_info,"我的")), ContactFragment.class,null);}
初始化 pager 并绑定适配器
/*** 初始化 pager 绑定适配器*/private void initPager() {fragments = new ArrayList<>();fragments.add(new DiscoverFragment());fragments.add(new AttachFragment());fragments.add(new MsgFragment());fragments.add(new ContactFragment());FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(),fragments);pager.setAdapter(adapter);}
分别给 TabHost 和pager 添加监听 实现联动
/*** 为TabHost和viewPager 添加监听 让其联动*/private void bindTabAndPager() {tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {/*** tab改变后* @param tabId 当前tab的tag*/@Overridepublic void onTabChanged(String tabId) {log("vonTabChanged:"+tabId);int position = tabHost.getCurrentTab();pager.setCurrentItem(position,true);}});pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {/*** 页面滑动 触发* @param position 当前显得第一个页面的索引,当滑动出现时屏幕就会显示两个pager, 向右滑 position为当前-1(左边的pager就显示出来了),向左滑position为当前(右面就显出来了),* @param positionOffset 0-1之间 position的偏移量 从原始位置的偏移量* @param positionOffsetPixels 从position偏移的像素值 从原始位置的便宜像素*/@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {log("onPageScrolled=============position:"+position+"====positionOffset:"+positionOffset+"====positionOffsetPixels:"+positionOffsetPixels);}/*** 页面选中后* @param position 当前页面的index*/@Overridepublic void onPageSelected(int position) {tabHost.setCurrentTab(position);log("onPageSelected==========:position:"+position);}/*** 页面滑动状态改变时触发* @param state 当前滑动状态 共三个状态值*/@Overridepublic void onPageScrollStateChanged(int state) {String stateStr="";switch (state){case ViewPager.SCROLL_STATE_DRAGGING:stateStr="正在拖动";break;case ViewPager.SCROLL_STATE_SETTLING:stateStr="正在去往最终位置 即将到达最终位置";break;case ViewPager.SCROLL_STATE_IDLE:stateStr="滑动停止,当前页面充满屏幕";break;}log("onPageScrollStateChanged========stateCode:"+state+"====state:"+stateStr);}});}
完整代码
public class TabPagerActivity extends AppCompatActivity {private static final String TAG ="TabPagerActivity";private FragmentTabHost tabHost;private ViewPager pager;private List<Fragment> fragments;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_tab_pager);tabHost = (FragmentTabHost) findViewById(R.id.tab_host);pager = (ViewPager) findViewById(R.id.pager);//初始化TabHostinitTabHost();//初始化pagerinitPager();//添加监听关联TabHost和viewPagerbindTabAndPager();}/*** 为TabHost和viewPager 添加监听 让其联动*/private void bindTabAndPager() {tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {/*** tab改变后* @param tabId 当前tab的tag*/@Overridepublic void onTabChanged(String tabId) {log("vonTabChanged:"+tabId);int position = tabHost.getCurrentTab();pager.setCurrentItem(position,true);}});pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {/*** 页面滑动 触发* @param position 当前显得第一个页面的索引,当滑动出现时屏幕就会显示两个pager, 向右滑 position为当前-1(左边的pager就显示出来了),向左滑position为当前(右面就显出来了),* @param positionOffset 0-1之间 position的偏移量 从原始位置的偏移量* @param positionOffsetPixels 从position偏移的像素值 从原始位置的便宜像素*/@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {log("onPageScrolled=============position:"+position+"====positionOffset:"+positionOffset+"====positionOffsetPixels:"+positionOffsetPixels);}/*** 页面选中后* @param position 当前页面的index*/@Overridepublic void onPageSelected(int position) {tabHost.setCurrentTab(position);log("onPageSelected==========:position:"+position);}/*** 页面滑动状态改变时触发* @param state 当前滑动状态 共三个状态值*/@Overridepublic void onPageScrollStateChanged(int state) {String stateStr="";switch (state){case ViewPager.SCROLL_STATE_DRAGGING:stateStr="正在拖动";break;case ViewPager.SCROLL_STATE_SETTLING:stateStr="正在去往最终位置 即将到达最终位置";break;case ViewPager.SCROLL_STATE_IDLE:stateStr="滑动停止,当前页面充满屏幕";break;}log("onPageScrollStateChanged========stateCode:"+state+"====state:"+stateStr);}});}/*** 初始化 pager 绑定适配器*/private void initPager() {fragments = new ArrayList<>();fragments.add(new DiscoverFragment());fragments.add(new AttachFragment());fragments.add(new MsgFragment());fragments.add(new ContactFragment());FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(),fragments);pager.setAdapter(adapter);}/*** 初始化 TabHost*/private void initTabHost() {tabHost.setup(this,getSupportFragmentManager(), R.id.pager);tabHost.getTabWidget().setDividerDrawable(null);tabHost.addTab(tabHost.newTabSpec("discover").setIndicator(createView(R.drawable.selector_bg,"发现")), DiscoverFragment.class,null);tabHost.addTab(tabHost.newTabSpec("attach").setIndicator(createView(R.drawable.selector_bg_attach,"关注")), AttachFragment.class,null);tabHost.addTab(tabHost.newTabSpec("message").setIndicator(createView(R.drawable.selector_bg_message,"消息")), MsgFragment.class,null);tabHost.addTab(tabHost.newTabSpec("info").setIndicator(createView(R.drawable.selector_bg_info,"我的")), ContactFragment.class,null);}/*** 返回view* @param icon* @param tab* @return*/private View createView(int icon,String tab){View view = getLayoutInflater().inflate(R.layout.fragment_tab_discover,null);ImageView imageView = (ImageView) view.findViewById(R.id.icon);TextView title = (TextView) view.findViewById(R.id.title);imageView.setImageResource(icon);title.setText(tab);return view;}private void log(String log){Log.e(TAG,"="+log+"=");}}
效果如下:
viewpager +TabLayout
TabLayout 输入 design的扩展包 使用之前必须得先导入扩展包
tabLayout 可以自动去关联 viewPager 只需为tabLayout 指定关联的viewPager就可以了
这样是方便了很多,但是也有缺点,在自动关联之后 tabLayout会自动去读取 viewPager的title,想使用自定的view当做tab就不可能了
导入 design 扩展包 并排在v7上面
布局 这里使用了两个TabLayout 分别实现 自动关联 和 手动关联
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"xmlns:app="http://schemas.android.com/apk/res-auto"android:id="@+id/activity_tab_layout"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="com.skymxc.demo.fragment.TabLayoutActivity"><!-- 使用自动关联--><android.support.design.widget.TabLayoutandroid:id="@+id/tab_layout"android:layout_width="match_parent"android:layout_height="wrap_content"app:tabMode="fixed"app:tabSelectedTextColor="#f0f"app:tabIndicatorColor="#f0f"></android.support.design.widget.TabLayout><android.support.v4.view.ViewPagerandroid:id="@+id/container"android:layout_width="match_parent"android:layout_height="0dp"android:layout_weight="1"></android.support.v4.view.ViewPager><!--通过监听去关联--><android.support.design.widget.TabLayoutandroid:id="@+id/tab_layout_menu"android:layout_width="match_parent"android:layout_height="wrap_content"app:tabMode="fixed"app:tabSelectedTextColor="#ff0"app:tabIndicatorColor="#ff0"></android.support.design.widget.TabLayout></LinearLayout>
初始化 自动关联的tab 并和viewPager绑定
private void initTabLayoutAndPager() {//关联 viewPager 使用关联后 tab就会自动去获取pager的title,使用addTab就会无效tabLayout.setupWithViewPager(pager);fragments = new ArrayList<>();fragments.add(new DiscoverFragment());fragments.add(new AttachFragment());fragments.add(new MsgFragment());fragments.add(new ContactFragment());adapter = new FragmentAdapter(getSupportFragmentManager(),fragments);pager.setAdapter(adapter);}
tab的布局和上面是一样的。
为TabLayout 添加view 自动关联添加也没用
tabLayoutMenu.addTab(tabLayoutMenu.newTab().setCustomView(createView(R.drawable.selector_bg,"发现")));tabLayoutMenu.addTab(tabLayoutMenu.newTab().setCustomView(createView(R.drawable.selector_bg_attach,"关注")));tabLayoutMenu.addTab(tabLayoutMenu.newTab().setCustomView(createView(R.drawable.selector_bg_message,"消息")));tabLayoutMenu.addTab(tabLayoutMenu.newTab().setCustomView(createView(R.drawable.selector_bg_info,"我的")));tabLayoutMenu.setSelectedTabIndicatorHeight(0);//去除指示器
设置 viewPager的监听和 TabLayout的监听 实现联动
tabLayoutMenu.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {/*** 选中tab后触发* @param tab 选中的tab*/@Overridepublic void onTabSelected(TabLayout.Tab tab) {//与pager 关联pager.setCurrentItem(tab.getPosition(),true);}/*** 退出选中状态时触发* @param tab 退出选中的tab*/@Overridepublic void onTabUnselected(TabLayout.Tab tab) {}/*** 重复选择时触发* @param tab 被 选择的tab*/@Overridepublic void onTabReselected(TabLayout.Tab tab) {}});pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Overridepublic void onPageSelected(int position) {//关联 TabLayouttabLayoutMenu.getTabAt(position).select();}@Overridepublic void onPageScrollStateChanged(int state) {}});
完整代码
package com.skymxc.demo.fragment;import android.support.design.widget.TabLayout;import android.support.v4.app.Fragment;import android.support.v4.view.ViewPager;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.ImageView;import android.widget.TextView;import com.skymxc.demo.fragment.adapter.FragmentAdapter;import com.skymxc.demo.fragment.fragment.AttachFragment;import com.skymxc.demo.fragment.fragment.ContactFragment;import com.skymxc.demo.fragment.fragment.DiscoverFragment;import com.skymxc.demo.fragment.fragment.MsgFragment;import java.util.ArrayList;import java.util.List;public class TabLayoutActivity extends AppCompatActivity {private TabLayout tabLayout;private ViewPager pager;private TabLayout tabLayoutMenu;private FragmentAdapter adapter ;private List<Fragment> fragments;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_tab_layout);tabLayout = (TabLayout) findViewById(R.id.tab_layout);pager = (ViewPager) findViewById(R.id.container);tabLayoutMenu = (TabLayout) findViewById(R.id.tab_layout_menu);initTabLayoutAndPager();//想使用自己的布局就得 通过 监听进行关联bindPagerAndTab();}private void bindPagerAndTab() {tabLayoutMenu.addTab(tabLayoutMenu.newTab().setCustomView(createView(R.drawable.selector_bg,"发现")));tabLayoutMenu.addTab(tabLayoutMenu.newTab().setCustomView(createView(R.drawable.selector_bg_attach,"关注")));tabLayoutMenu.addTab(tabLayoutMenu.newTab().setCustomView(createView(R.drawable.selector_bg_message,"消息")));tabLayoutMenu.addTab(tabLayoutMenu.newTab().setCustomView(createView(R.drawable.selector_bg_info,"我的")));tabLayoutMenu.setSelectedTabIndicatorHeight(0);//去除指示器tabLayoutMenu.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {/*** 选中tab后触发* @param tab 选中的tab*/@Overridepublic void onTabSelected(TabLayout.Tab tab) {//与pager 关联pager.setCurrentItem(tab.getPosition(),true);}/*** 退出选中状态时触发* @param tab 退出选中的tab*/@Overridepublic void onTabUnselected(TabLayout.Tab tab) {}/*** 重复选择时触发* @param tab 被 选择的tab*/@Overridepublic void onTabReselected(TabLayout.Tab tab) {}});pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}@Overridepublic void onPageSelected(int position) {//关联 TabLayouttabLayoutMenu.getTabAt(position).select();}@Overridepublic void onPageScrollStateChanged(int state) {}});}private void initTabLayoutAndPager() {//关联 viewPager 使用关联后 tab就会自动去获取pager的title,使用addTab就会无效tabLayout.setupWithViewPager(pager);fragments = new ArrayList<>();fragments.add(new DiscoverFragment());fragments.add(new AttachFragment());fragments.add(new MsgFragment());fragments.add(new ContactFragment());adapter = new FragmentAdapter(getSupportFragmentManager(),fragments);pager.setAdapter(adapter);}private View createView(int icon, String tab){View view = getLayoutInflater().inflate(R.layout.fragment_tab_discover,null);ImageView imageView = (ImageView) view.findViewById(R.id.icon);TextView title = (TextView) view.findViewById(R.id.title);imageView.setImageResource(icon);title.setText(tab);return view;}}
效果图
这里贴一下 viewPager的适配器
public class FragmentAdapter extends FragmentPagerAdapter {List<Fragment> fragments ;private String[] titles = new String[]{"发现","关注","消息","我的"};public FragmentAdapter(FragmentManager fm,List<Fragment> fragments) {super(fm);this.fragments =fragments;}@Overridepublic Fragment getItem(int position) {return fragments.get(position);}@Overridepublic int getCount() {return fragments ==null ?0:fragments.size();}@Overridepublic CharSequence getPageTitle(int position) {return titles[position];}}
目前就总结了这几种方式 想到别的方式 再总结
关于这个 Demo的github :https://github.com/sky-mxc/AndroidDemo/tree/master/fragment
以上所示是小编给大家介绍的Android开发之微信底部菜单栏实现的几种方法汇总,希望对大家有所帮助!
新闻热点
疑难解答