Fragment实现底部导航栏,TabLayout双向交互联动切换

2020-03-17 07:38 来源:未知

导包TabLayout,要增加的援用。

MessageGroupFragmentAdapter.java    ViewPager的适配器.

二、创设主布局

 

字体颜色选拔器:tab_text_color.xml

adapter = new MessageGroupFragmentAdapter(getChildFragmentManager(), list);

一、在库中拉长重视

 

因为要使用TabLayout,

图表接受器   tab_item_main_img_selector.xml

这里上方为ViewPager,下边是TabLayout

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     xmlns:app="http://schemas.android.com/apk/res-auto"
 4     android:orientation="vertical"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent" >
 7 
 8     <!-- app:tabIndicatorColor 指示器(字体下面的那一个横)显示颜色 -->
 9     <!-- app:tabSelectedTextColor 选中的字体颜色 -->
10     <!-- app:tabTextColor 未选中的字体颜色 -->
11 
12     <android.support.design.widget.TabLayout
13         android:id="@ id/tabLayout"
14         android:layout_width="match_parent"
15         android:layout_height="wrap_content"
16         app:tabIndicatorColor="#26c6da"
17         app:tabSelectedTextColor="#f44336"
18         app:tabTextColor="#bdbdbd" />
19 
20     <android.support.v4.view.ViewPager
21         android:id="@ id/viewPager"
22         android:layout_weight="1"
23         android:layout_width="match_parent"
24         android:layout_height="wrap_content" />
25 
26 </LinearLayout>

谢谢观望!希望对您抱有助于!你的协理是自身的重力!如有疑问 联系QQ:563084073。

MainFragment.java  首页有四个页面(关心,推荐,动态State of Qatar,作者使用了ViewPager滑动,扩张了滑动提示状态.並且给标题栏的三个TextView设置了点击效果.

五、Activity代码:

美高梅网投平台, 

TabLayout的style="@style/MainTabLayout"。注释很清晰,不再累赘。

有关小说:伊夫ntBus实现activity跟fragment人机联作数据

接下去牵头详细记录:

MainActivity.java要求的布局文件:activity_main.xml:

MainFragment的布局文件:main_f.xml。

主界面布局文件  activity_main.xml   外层四个FrameLayout ImageView LinearLayout     TextView选中跟未入选时 图片和颜料 切换都用构造去完结.

导航栏图片选取器:tab_mine_selector.xml(这里以内部三个为例,“小编” 的入选效果卡塔尔国

数见不鲜,android.support.design.widget.TabLayout与Android的ViewPager联合使用,达成与ViewPager的切换与联合浮动。
(1)举例,当顾客手指触摸选用TabLayout中的某一项时候,ViewPager应当自行切换跳转到相应的Page页面;
(2)相同,当客商在查看ViewPager时候,TabLayout也会活动的轮转到与眼下ViewPager页面像对应的子item tab并使该子item tab处于选中状态。

compile'com.android.support:design:25.0.0'

一.先上效益图:   本来是希图用FragmentTabHost达成的,然则中间那多少个按键有一点点麻烦,想到大家项目大多少个成品主任,而且临时改要求,于是最终决定  用 TextView Fragment去达成.                     

后边的博文写到了TabLayout完结了选项卡的构造,前几日练习八个app发现须求叁个导航栏在尾部的app,在那记录一下,其实就是TabLayout和ViewPager布局顺序换一下就足以了。

美高梅网投平台 1

<?xml version="1.0" encoding="utf-8"?><selector xmlns:andro> <item android:drawable="@drawable/tab_bar_1_1" android:state_selected="true"/><!--选中时候显示的图片--> <item android:drawable="@drawable/tab_bar_1" android:state_selected="false"/><!--默认没有选中的图片--></selector>

序言:项目第二版刚上线没多长期,成品又对供给开展了大改观,在此之前用的是左滑菜单,未来又要换到尾巴部分导航栏,于是明天又苦逼加班了.花了多少个时辰达成了三个底层导航栏的demo,然后总括一下.写一篇博客.供本身之后参照他事他说加以考查.也能够给未有做过的心上人进行参考.以后大家有临近的功效就能够在本身的demo上就能够修正.

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.LayoutInflater;

import android.view.View;

import android.widget.ImageView;

import android.widget.TextView;

import com.example.wjy329.bodybuilding.adapter.ViewPagerAdapter;

import com.example.wjy329.bodybuilding.fragment.BuildFragment;

import com.example.wjy329.bodybuilding.fragment.DynamicFragment;

import com.example.wjy329.bodybuilding.fragment.FindFragment;

import com.example.wjy329.bodybuilding.fragment.MineFragment;

public class MainActivity extends AppCompatActivity {

private TabLayout mTabLayout;

//Tab文字

private final int[] TAB_TITLES = new int[]{

R.string.build,R.string.find,R.string.dynamic,R.string.mine

};

//Tab图片

private final int[] TAB_IMGS = new int[]{

R.drawable.tab_build_selector,R.drawable.tab_find_selector,R.drawable.tab_dynamic_selector,R.drawable.tab_mine_selector

};

//Tab数目

private final Fragment[] TAB_FRAGMENTS = new Fragment[]{

new BuildFragment(),new FindFragment(),new DynamicFragment(),new MineFragment()

};

private ViewPagerAdapter mViewPagerAdapter;//适配器

private ViewPager mViewPager;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

initViews();

}

private void initViews() {

mTabLayout = (TabLayout) findViewById(R.id.tablayout);

setTabs(mTabLayout,this.getLayoutInflater(),TAB_TITLES,TAB_IMGS);

mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),TAB_FRAGMENTS);

mViewPager = (ViewPager) findViewById(R.id.viewpager);

mViewPager.setAdapter(mViewPagerAdapter);

mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));//滑动效果

mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));//点击效果

}

private void setTabs(TabLayout tabLayout, LayoutInflater inflater, int[] tabTitlees, int[] tabImgs) {

for (int i = 0; i < tabImgs.length; i  ) {

TabLayout.Tab tab = tabLayout.newTab();

View view = inflater.inflate(R.layout.tab_custom,null);

tab.setCustomView(view);

TextView tvTitle = (TextView)view.findViewById(R.id.tv_tab);

tvTitle.setText(tabTitlees[i]);

ImageView imgTab = (ImageView) view.findViewById(R.id.img_tab);

imgTab.setImageResource(tabImgs[i]);

tabLayout.addTab(tab);

}

}

}
 1 package com.zzw.testtablayout;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 import android.support.design.widget.TabLayout;
 6 import android.support.v4.view.PagerAdapter;
 7 import android.support.v4.view.ViewPager;
 8 import android.view.Gravity;
 9 import android.view.View;
10 import android.view.ViewGroup;
11 import android.widget.TextView;
12 
13 public class MainActivity extends Activity {
14 
15     private final int COUNT = 10;
16 
17     @Override
18     protected void onCreate(Bundle savedInstanceState) {
19         super.onCreate(savedInstanceState);
20         setContentView(R.layout.activity_main);
21 
22         TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
23 
24         tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
25 
26         ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
27         viewPager.setAdapter(new MyAdapter(this));
28 
29         // TabLayout和ViewPager双向、交互联动。
30         tabLayout.setupWithViewPager(viewPager);
31     }
32 
33     private class MyAdapter extends PagerAdapter {
34         private Activity activity;
35 
36         public MyAdapter(Activity activity) {
37             this.activity = activity;
38         }
39 
40         @Override
41         public CharSequence getPageTitle(int position) {
42 
43             return "选项"   position;
44         }
45 
46         @Override
47         public Object instantiateItem(View container, int position) {
48             TextView tv = new TextView(activity);
49             tv.setText("ViewPager"   position);
50             tv.setTextSize(30.0f);
51             tv.setGravity(Gravity.CENTER);
52 
53             ((ViewGroup) container).addView(tv);
54             return tv;
55         }
56 
57         @Override
58         public void destroyItem(View container, int position, Object object) {
59             ((ViewPager) container).removeView((View) object);
60 
61         }
62 
63         @Override
64         public int getCount() {
65             return COUNT;
66         }
67 
68         @Override
69         public boolean isViewFromObject(View arg0, Object arg1) {
70             return arg0 == arg1;
71         }
72 
73     }
74 }
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:andro android:layout_width="match_parent" android:layout_height="44dp" android:orientation="vertical"> <ImageView android: android:layout_width="match_parent" android:layout_height="28dp" android:src="@drawable/bottombar_01" /> <TextView android: android:layout_width="match_parent" android:layout_height="16dp" android:gravity="center" android:text="首页" android:textColor="@drawable/tab_text_color" /></LinearLayout>

后记:假诺你运营之后首页会鬼使神差空白的图景,viewpager滑动也会现身难题了,那是MainFragment类初叶化viewpager的adpater有毛病.

四、导航栏构造文件、导航栏选取器文件

测量检验用的主Activity MainActivity.java :

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:andro xmlns:app="http://schemas.android.com/apk/res-auto" android: android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v4.view.ViewPager android: android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@color/main_bg" /> <android.support.design.widget.TabLayout android: android:layout_width="match_parent" android:layout_height="wrap_content" style="@style/MainTabLayout" app:tabMode="fixed" /></LinearLayout>
/**
 * 对fragment的切换,底部图标颜色的切换
 * @author ansen
 * @create time 2015-09-08
 */
public class MainActivity extends FragmentActivity {
    //要切换显示的四个Fragment
    private MainFragment mainFragment;
    private DynamicFragment dynamicFragment;
    private MessageFragment messageFragment;
    private PersonFragment personFragment;

    private int currentId = R.id.tv_main;// 当前选中id,默认是主页

    private TextView tvMain, tvDynamic, tvMessage, tvPerson;//底部四个TextView

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvMain = (TextView) findViewById(R.id.tv_main);
        tvMain.setSelected(true);//首页默认选中
        tvDynamic = (TextView) findViewById(R.id.tv_dynamic);
        tvMessage = (TextView) findViewById(R.id.tv_message);
        tvPerson = (TextView) findViewById(R.id.tv_person);

        /**
         * 默认加载首页
         */
        mainFragment = new MainFragment();
        getSupportFragmentManager().beginTransaction().add(R.id.main_container, mainFragment).commit();

        tvMain.setOnClickListener(tabClickListener);
        tvDynamic.setOnClickListener(tabClickListener);
        tvMessage.setOnClickListener(tabClickListener);
        tvPerson.setOnClickListener(tabClickListener);
        findViewById(R.id.iv_make).setOnClickListener(onClickListener);
    }

    private OnClickListener onClickListener=new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.iv_make:
                Intent intent=new Intent(MainActivity.this, MakeActivity.class);
                startActivity(intent);
                break;
            }
        }
    };

    private OnClickListener tabClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() != currentId) {//如果当前选中跟上次选中的一样,不需要处理
                changeSelect(v.getId());//改变图标跟文字颜色的选中 
                changeFragment(v.getId());//fragment的切换
                currentId = v.getId();//设置选中id
            }
        }
    };

    /**
     * 改变fragment的显示
     * 
     * @param resId
     */
    private void changeFragment(int resId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();//开启一个Fragment事务

        hideFragments(transaction);//隐藏所有fragment
        if(resId==R.id.tv_main){//主页
            if(mainFragment==null){//如果为空先添加进来.不为空直接显示
                mainFragment = new MainFragment();
                transaction.add(R.id.main_container,mainFragment);
            }else {
                transaction.show(mainFragment);
            }
        }else if(resId==R.id.tv_dynamic){//动态
            if(dynamicFragment==null){
                dynamicFragment = new DynamicFragment();
                transaction.add(R.id.main_container,dynamicFragment);
            }else {
                transaction.show(dynamicFragment);
            }
        }else if(resId==R.id.tv_message){//消息中心
            if(messageFragment==null){
                messageFragment = new MessageFragment();
                transaction.add(R.id.main_container,messageFragment);
            }else {
                transaction.show(messageFragment);
            }
        }else if(resId==R.id.tv_person){//我
            if(personFragment==null){
                personFragment = new PersonFragment();
                transaction.add(R.id.main_container,personFragment);
            }else {
                transaction.show(personFragment);
            }
        }
        transaction.commit();//一定要记得提交事务
    }

    /**
     * 显示之前隐藏所有fragment
     * @param transaction
     */
    private void hideFragments(FragmentTransaction transaction){
        if (mainFragment != null)//不为空才隐藏,如果不判断第一次会有空指针异常
            transaction.hide(mainFragment);
        if (dynamicFragment != null)
            transaction.hide(dynamicFragment);
        if (messageFragment != null)
            transaction.hide(messageFragment);
        if (personFragment != null)
            transaction.hide(personFragment);
    }

    /**
     * 改变TextView选中颜色
     * @param resId
     */
    private void changeSelect(int resId) {
        tvMain.setSelected(false);
        tvDynamic.setSelected(false);
        tvMessage.setSelected(false);
        tvPerson.setSelected(false);

        switch (resId) {
        case R.id.tv_main:
            tvMain.setSelected(true);
            break;
        case R.id.tv_dynamic:
            tvDynamic.setSelected(true);
            break;
        case R.id.tv_message:
            tvMessage.setSelected(true);
            break;
        case R.id.tv_person:
            tvPerson.setSelected(true);
            break;
        }
    }
}

惯例,先加信任(依版本增添State of Qatar

import android.os.Bundle;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import android.view.ViewGroup;public class MainPageAdapter extends FragmentPagerAdapter{ Fragment[] fragments; public MainPageAdapter(FragmentManager fm,Fragment[] fragments){ super; this.fragments = fragments; } @Override public int getCount() { if(fragments==null){ return 0; } return fragments.length; } @Override public Fragment getItem(int position) { Bundle bundle = new Bundle(); bundle.putInt("position",position); fragments[position].setArguments; return fragments[position]; } @Override public int getItemPosition(Object object) { return super.getItemPosition; } @Override public long getItemId(int position){ return super.getItemId; } @Override public void destroyItem(ViewGroup container, int position, Object object){ super.destroyItem(container,position,object); }}
<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" >

    <FrameLayout
        android:id="@ id/main_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@ id/view_line"/>

    <View
        android:id="@ id/view_line"
        android:layout_height="1dp"
        android:layout_width="match_parent"
        android:background="#DCDBDB"
        android:layout_above="@ id/rl_bottom"/>

    <LinearLayout
        android:id="@ id/rl_bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:background="#F2F2F2"
        android:orientation="horizontal" >

        <TextView
            android:id="@ id/tv_main"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:drawableTop="@drawable/tab_item_main_img_selector"
            android:drawablePadding="@dimen/main_tab_item_image_and_text"
            android:focusable="true"
            android:gravity="center"
            android:text="@string/main"
            android:textColor="@drawable/tabitem_txt_sel" />

        <TextView
            android:id="@ id/tv_dynamic"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:drawableTop="@drawable/tab_item_dynamic_img_selector"
            android:drawablePadding="@dimen/main_tab_item_image_and_text"
            android:focusable="true"
            android:gravity="center"
            android:text="@string/dynamic"
            android:textColor="@drawable/tabitem_txt_sel" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TextView
            android:id="@ id/tv_message"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:drawableTop="@drawable/tab_item_message_img_selector"
            android:drawablePadding="@dimen/main_tab_item_image_and_text"
            android:focusable="true"
            android:gravity="center"
            android:text="@string/message"
            android:textColor="@drawable/tabitem_txt_sel" />

        <TextView
            android:id="@ id/tv_person"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:drawableTop="@drawable/tab_item_person_img_selector"
            android:drawablePadding="@dimen/main_tab_item_image_and_text"
            android:focusable="true"
            android:gravity="center"
            android:text="@string/person"
            android:textColor="@drawable/tabitem_txt_sel"/>
    </LinearLayout>

    <ImageView
        android:id="@ id/iv_make"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:paddingBottom="10dp"
        android:src="@drawable/icon_tab_make_select"/>

</RelativeLayout>

 

import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; public class MainFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.main_f,null); TextView textView =  view.findViewById(R.id.textview); int position = getArguments().getInt("position",0); textView.setText("textView------position=" position); return view; }}

文字颜色选择器   tabitem_txt_sel.xml

MainActivity.java

适配器:MainPageAdapter.java

二.查看代码达成.代码是我们最佳的老师.

美高梅网投平台 2

图片选取器:bottombar_01.xml。【总共有多少个,这里就显得一个】

点击下载源码

三、写ViewPager的Adapter文件

TabLayout的子成分Tab的构造View文件main_tab.xml

改革后代码如下,大概在MainFragment中125行:

compile 'com.android.support:design:25.2.0'

import android.support.design.widget.TabLayout;

MainActivity.java   对fragment的切换,尾部Logo颜色的切换.小编也不详细介绍了.代码里面笔者都有写注释.

ViewPagerAdapter.java

主类:MainA.java。注释很清楚,不再累赘。

本条demo的中央代码就在这里处了,别的多少个Fragment的代码跟构造文件作者就不贴出来了....有亟待的能够去下载小编的源码.....又到了10点半了....回家.....

意义图先放上来:

美高梅网投平台 3main_tab.xml

2State of Qatar.ImageView  展现尾部最中间那叁个图标

选择器:

美高梅网投平台 4底层导航作用图

美高梅网投平台 5

import android.support.v4.app.Fragment;

import android.support.v4.app.FragmentManager;

import android.support.v4.app.FragmentStatePagerAdapter;

import java.util.List;

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

private Fragment[] mFragments;

public ViewPagerAdapter(FragmentManager fm, Fragment[] fragments) {

super(fm);

mFragments = fragments;

}

@Override

public Fragment getItem(int position) {

return mFragments[position];

}

@Override

public int getCount() {

return mFragments.length;

}

}
import android.os.Bundle;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.view.LayoutInflater;import android.view.View;import android.widget.ImageView;import android.widget.TextView;public class MainA extends AppCompatActivity { private Fragment[] fragments = {new MainFragment(), new MainFragment(), new MainFragment(), new MainFragment(), new MainFragment()}; private int[] imgs = {R.drawable.bottombar_01, R.drawable.bottombar_02, R.drawable.bottombar_03, R.drawable.bottombar_04, R.drawable.bottombar_05 }; private String[] names = {"tab1", "tab2", "tab3", "tab4", "tab5" }; private TabLayout tabLayout; private MainPageAdapter adapter;//PageAdapter适配器 private ViewPager container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_a); initView();//初始化布局组件 setView();//对组件按需求进行相关属性设置 } public void initView(){ tabLayout = (TabLayout) findViewById(R.id.main_tablayout); adapter = new MainPageAdapter(getSupportFragmentManager(),fragments); container = (ViewPager) findViewById(R.id.container); } public void setView(){ tabLayout.setTabMode(TabLayout.MODE_FIXED); container.setAdapter; tabLayout.setupWithViewPager(container,false );//第二个参数autoRefresh:是否自动刷新(切换的时候是否刷PagerAdapter选中的Fragment) //以下是对TabLayout进行相关设置 int tabCount = tabLayout.getTabCount();//获取TabLayout的个数 for (int i=0; i<tabCount; i  ) { View view = LayoutInflater.from(MainA.this).inflate(R.layout.main_tab,null); ImageView imageView = (ImageView) view.findViewById(R.id.main_tab_img); imageView.setImageDrawable(getResources().getDrawable; TextView textView =  view.findViewById(R.id.main_tab_tv); textView.setText; TabLayout.Tab tab = tabLayout.getTabAt;////获取TabLayout的子元素Tab tab.setCustomView;//设置TabLayout的子元素Tab的布局View } }}

1卡塔尔(قطر‎.FrameLayout  用于展示fragment

导航栏文字接纳器:tv_tab_selector.xml

先上主类的结构文件:main_a.xml

/**
 * 首页
 * @author Ansen
 * @create time 2015-09-08
 */
public class MainFragment extends Fragment {
    private ViewPager vPager;
    private List<Fragment> list = new ArrayList<Fragment>();
    private MessageGroupFragmentAdapter adapter;

    private ImageView ivShapeCircle;
    private TextView tvFollow,tvRecommend,tvLocation;

    private int offset=0;//偏移量216  我这边只是举例说明,不同手机值不一样
    private int currentIndex=1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, null);


        /**
         * 初始化三个Fragment  并且填充到ViewPager
         */
        vPager = (ViewPager) rootView.findViewById(R.id.viewpager_home);
        DynamicFragment dynamicFragment = new DynamicFragment();
        MessageFragment messageFragment = new MessageFragment();
        PersonFragment personFragment = new PersonFragment();
        list.add(dynamicFragment);
        list.add(messageFragment);
        list.add(personFragment);
        adapter = new MessageGroupFragmentAdapter(getActivity().getSupportFragmentManager(), list);
        vPager.setAdapter(adapter);
        vPager.setOffscreenPageLimit(2);
        vPager.setCurrentItem(1);
        vPager.setOnPageChangeListener(pageChangeListener);


        ivShapeCircle = (ImageView) rootView.findViewById(R.id.iv_shape_circle);

        tvFollow=(TextView) rootView.findViewById(R.id.tv_follow);
        tvRecommend=(TextView) rootView.findViewById(R.id.tv_recommend);
        tvRecommend.setSelected(true);//推荐默认选中
        tvLocation=(TextView) rootView.findViewById(R.id.tv_location);

        /**
         * 标题栏三个按钮设置点击效果
         */
        tvFollow.setOnClickListener(clickListener);
        tvRecommend.setOnClickListener(clickListener);
        tvLocation.setOnClickListener(clickListener);

        initCursorPosition();
        return rootView;
    }

    private OnClickListener clickListener=new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.tv_follow:
                //当我们设置setCurrentItem的时候就会触发viewpager的OnPageChangeListener借口,
                //所以我们不需要去改变标题栏字体啥的
                vPager.setCurrentItem(0);
                break;
            case R.id.tv_recommend:
                vPager.setCurrentItem(1);
                break;
            case R.id.tv_location:
                vPager.setCurrentItem(2);
                break;
            }
        }
    };

    private void initCursorPosition() {
        DisplayMetrics metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;
        Matrix matrix = new Matrix();

        //标题栏我用weight设置权重  分成5份
        //(width / 5) * 2  这里表示标题栏两个控件的宽度
        //(width / 10)  标题栏一个控件的2分之一
        //7  约等于原点宽度的一半
        matrix.postTranslate((width / 5) * 2   (width / 10)-7,0);//图片平移
        ivShapeCircle.setImageMatrix(matrix);

        //一个控件的宽度  我的手机宽度是1080/5=216 不同的手机宽度会不一样哦
        offset=(width / 5);
    }

    /**
     * ViewPager滑动监听,用位移动画实现指示器效果
     * 
     * TranslateAnimation 强调一个地方,无论你移动了多少次,现在停留在哪里,你的起始位置从未变化过.
     * 例如:我这个demo里面  推荐移动到了同城,指示器也停留到了同城下面,但是指示器在屏幕上的位置还是推荐下面.
     */
    private OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
        @Override
        public void onPageSelected(int index) {
            changeTextColor(index);
            translateAnimation(index);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    };

    /**
     * 改变标题栏字体颜色
     * @param index
     */
    private void changeTextColor(int index){
        tvFollow.setSelected(false);
        tvRecommend.setSelected(false);
        tvLocation.setSelected(false);

        switch (index) {
        case 0:
            tvFollow.setSelected(true);
            break;
        case 1:
            tvRecommend.setSelected(true);
            break;
        case 2:
            tvLocation.setSelected(true);
            break;
        }
    }

    /**
     * 移动标题栏点点点...
     * @param index
     */
    private void translateAnimation(int index){
        TranslateAnimation animation = null;
        switch(index){
        case 0:
            if(currentIndex==1){//从推荐移动到关注   X坐标向左移动216
                animation=new TranslateAnimation(0,-offset,0,0);
            }else if (currentIndex == 2) {//从同城移动到关注   X坐标向左移动216*2  记住起始x坐标是同城那里
                animation = new TranslateAnimation(offset, -offset, 0, 0);  
            }
            break;
        case 1:
            if(currentIndex==0){//从关注移动到推荐   X坐标向右移动216
                    animation=new TranslateAnimation(-offset,0,0,0);
            }else if(currentIndex==2){//从同城移动到推荐   X坐标向左移动216
                animation=new TranslateAnimation(offset, 0,0,0);
            }
            break;
        case 2:
            if (currentIndex == 0) {//从关注移动到同城   X坐标向右移动216*2  记住起始x坐标是关注那里
                animation = new TranslateAnimation(-offset, offset, 0, 0);
            } else if(currentIndex==1){//从推荐移动到同城   X坐标向右移动216
                animation=new TranslateAnimation(0,offset,0,0);
            }
            break;
        }
        animation.setFillAfter(true);
        animation.setDuration(300);
        ivShapeCircle.startAnimation(animation);

        currentIndex=index;
    }
}

布局:tab_layout.xml

<style name="MainTabLayout"> <item name="tabIndicatorColor">@android:color/transparent</item> <!-- tabLayout 底部选择状态横线的的颜色:透明 --> <item name="tabIndicatorHeight">0dp</item><!-- tabLayout 底部选择状态横线的高度:0 --> <item name="tabPaddingStart">12dp</item> <item name="tabPaddingEnd">12dp</item></style>

3卡塔尔国.LinearLayout  呈现底部三个Logo   作者这里用weight分成了5份,第八个控件啥都未有就用View控件占了二个岗位

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:andro android: android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android: android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"/></LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Non focused states -->
    <item android:state_focused="false" android:state_pressed="false" android:state_selected="false" android:color="@color/main_tab_item_text_normal"/>
    <item android:state_focused="false" android:state_pressed="false" android:state_selected="true" android:color="@color/main_tab_item_text_select"/>

    <!-- Focused states -->
    <item android:state_focused="true" android:state_pressed="false" android:state_selected="false" android:color="@color/main_tab_item_text_select"/>
    <item android:state_focused="true" android:state_pressed="false" android:state_selected="true" android:color="@color/main_tab_item_text_select"/>

    <!-- Pressed -->
    <item android:state_pressed="true" android:state_selected="true" android:color="@color/main_tab_item_text_select"/>
    <item android:state_pressed="true" android:color="@color/main_tab_item_text_select"/>

</selector>
<?xml version="1.0" encoding="utf-8"?><selector xmlns:andro> <!-- Non focused states --> <item android:state_focused="false" android:state_pressed="false" android:state_selected="false" android:color="@color/main_tab_text"/> <item android:state_focused="false" android:state_pressed="false" android:state_selected="true" android:color="@color/main_tab_text_selected"/> <!-- Focused states --> <item android:state_focused="true" android:state_pressed="false" android:state_selected="false" android:color="@color/main_tab_text_selected"/> <item android:state_focused="true" android:state_pressed="false" android:state_selected="true" android:color="@color/main_tab_text_selected"/> <!-- Pressed --> <item android:state_pressed="true" android:state_selected="true" android:color="@color/main_tab_text_selected"/> <item android:state_pressed="true" android:color="@color/main_tab_text_selected"/></selector>

首页展现的MainFragment.java的布局文件  fragment_main.xml 

要么勤快一点,让我们更清楚,把MainFragment.java粘贴出来。

public class MessageGroupFragmentAdapter extends FragmentStatePagerAdapter {
    private List<Fragment>list;
    public MessageGroupFragmentAdapter(FragmentManager fm, List<Fragment> list) {
        super(fm);
        this.list = list;
    }

    public MessageGroupFragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int arg0) {
        return list.get(arg0);
    }

    @Override
    public int getCount() {
        return list.size();
    }
}

国际惯例:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Non focused states -->
    <item android:drawable="@drawable/icon_tab_main_normal" android:state_focused="false" android:state_pressed="false" android:state_selected="false"/>
    <item android:drawable="@drawable/icon_tab_main_select" android:state_focused="false" android:state_pressed="false" android:state_selected="true"/>
    <!-- Focused states -->
    <item android:drawable="@drawable/icon_tab_main_select" android:state_focused="true" android:state_pressed="false" android:state_selected="false"/>
    <item android:drawable="@drawable/icon_tab_main_select" android:state_focused="true" android:state_pressed="false" android:state_selected="true"/>
    <!-- Pressed -->
    <item android:drawable="@drawable/icon_tab_main_select" android:state_pressed="true" android:state_selected="true"/>
    <item android:drawable="@drawable/icon_tab_main_select" android:state_pressed="true"/>
</selector>
<?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="match_parent" >

    <LinearLayout
        android:id="@ id/ll_title"
        android:layout_width="match_parent"
        android:layout_height="44dp"
        android:background="#00ceaa"
        android:orientation="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="30dp"
            android:orientation="horizontal" >

            <View
                android:id="@ id/view_empty"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" />

            <TextView
                android:id="@ id/tv_follow"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:paddingTop="5dp"
                android:text="关注"
                android:gravity="center_horizontal"
                android:textColor="@drawable/main_title_txt_sel"
                android:textSize="20sp" />

            <TextView
                android:id="@ id/tv_recommend"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:paddingTop="5dp"
                android:text="推荐"
                android:gravity="center_horizontal"
                android:textColor="@drawable/main_title_txt_sel"
                android:textSize="20sp" />

            <TextView
                android:id="@ id/tv_location"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:paddingTop="5dp"
                android:text="同城"
                android:gravity="center_horizontal"
                android:textColor="@drawable/main_title_txt_sel"
                android:textSize="20sp" />

            <View
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1" />
        </LinearLayout>

        <ImageView
            android:id="@ id/iv_shape_circle"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:scaleType="matrix"
            android:src="@drawable/shape_circle" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@ id/viewpager_home"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@ id/ll_title" />

</RelativeLayout>
TAG标签:
版权声明:本文由美高梅网投平台发布于美高梅网投网址,转载请注明出处:Fragment实现底部导航栏,TabLayout双向交互联动切换