ViewPage实现tab页

在这里插入图片描述

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="48dp"
    android:background="#FFFFFF">

    <TextView
        android:id="@+id/tv_one"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1.0"
        android:gravity="center"
        android:text="橘黄"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/tv_two"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1.0"
        android:gravity="center"
        android:text="淡黄"
        android:textColor="#000000" />

    <TextView
        android:id="@+id/tv_three"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1.0"
        android:gravity="center"
        android:text="浅棕"
        android:textColor="#000000" />
</LinearLayout>

<ImageView
    android:id="@+id/img_cursor"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scaleType="matrix"
    android:src="@mipmap/line" />

<android.support.v4.view.ViewPager
    android:id="@+id/vpager_four"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_gravity="center"
    android:layout_weight="1.0"
    android:flipInterval="30"   //动画间隔
    android:persistentDrawingCache="animation"    //缓存策略
    />

接着到我们的Activity了,我们来捋下思路:

Step 1:我们需要让我们的移动块在第一个文字下居中,那这里就要算一下偏移量: 先获得图片宽度pw,然后获取屏幕宽度sw,计算方法很简单:
offset(偏移量) = ((sw / 3)-pw) / 2 //屏幕宽/3 - 图片宽度,然后再除以2,左右嘛!
然后我么你调用setImageMatrix设置滑块当前的位置: 同时我们也把切换一页和两页,滑块的移动距离也算出来,很简单: one =
offset * 2 + pw; two = one * 2;

Step 2:当我们滑动页面时,我们的滑块要进行移动,我们要为ViewPager添加一个
OnPageChangeListener事件,我们需要对滑动后的页面来做一个判断,同时记录滑动前处于
哪个页面,下面自己画了个图,可能更容易理解吧!
在这里插入图片描述

/**
 * Created by Jay on 2015/10/8 0008.
 */
public class FourActivity extends AppCompatActivity implements View.OnClickListener,
        ViewPager.OnPageChangeListener {

    private ViewPager vpager_four;
    private ImageView img_cursor;
    private TextView tv_one;
    private TextView tv_two;
    private TextView tv_three;

    private ArrayList<View> listViews;
    private int offset = 0;//移动条图片的偏移量
    private int currIndex = 0;//当前页面的编号
    private int bmpWidth;// 移动条图片的长度
    private int one = 0; //移动条滑动一页的距离
    private int two = 0; //滑动条移动两页的距离

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_four);
        initViews();
    }


    private void initViews() {
        vpager_four = (ViewPager) findViewById(R.id.vpager_four);
        tv_one = (TextView) findViewById(R.id.tv_one);
        tv_two = (TextView) findViewById(R.id.tv_two);
        tv_three = (TextView) findViewById(R.id.tv_three);
        img_cursor = (ImageView) findViewById(R.id.img_cursor);

        //下划线动画的相关设置:
        bmpWidth = BitmapFactory.decodeResource(getResources(), R.mipmap.line).getWidth();// 获取图片宽度
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenW = dm.widthPixels;// 获取分辨率宽度
        offset = (screenW / 3 - bmpWidth) / 2;// 计算偏移量
        Matrix matrix = new Matrix();
        matrix.postTranslate(offset, 0);
        img_cursor.setImageMatrix(matrix);// 设置动画初始位置
        //移动的距离
        one = offset * 2 + bmpWidth;// 移动一页的偏移量,比如1->2,或者2->3
        two = one * 2;// 移动两页的偏移量,比如1直接跳3


        //往ViewPager填充View,同时设置点击事件与页面切换事件
        listViews = new ArrayList<View>();
        LayoutInflater mInflater = getLayoutInflater();
        listViews.add(mInflater.inflate(R.layout.view_one, null, false));
        listViews.add(mInflater.inflate(R.layout.view_two, null, false));
        listViews.add(mInflater.inflate(R.layout.view_three, null, false));
        vpager_four.setAdapter(new MyPagerAdapter(listViews));
        vpager_four.setCurrentItem(0);          //设置ViewPager当前页,从0开始算

        tv_one.setOnClickListener(this);
        tv_two.setOnClickListener(this);
        tv_three.setOnClickListener(this);

        vpager_four.addOnPageChangeListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_one:
                vpager_four.setCurrentItem(0);
                break;
            case R.id.tv_two:
                vpager_four.setCurrentItem(1);
                break;
            case R.id.tv_three:
                vpager_four.setCurrentItem(2);
                break;
        }
    }

    @Override
    public void onPageSelected(int index) {
        Animation animation = null;
        switch (index) {
            case 0:
                if (currIndex == 1) {
                    animation = new TranslateAnimation(one, 0, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, 0, 0, 0);
                }
                break;
            case 1:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, one, 0, 0);
                } else if (currIndex == 2) {
                    animation = new TranslateAnimation(two, one, 0, 0);
                }
                break;
            case 2:
                if (currIndex == 0) {
                    animation = new TranslateAnimation(offset, two, 0, 0);
                } else if (currIndex == 1) {
                    animation = new TranslateAnimation(one, two, 0, 0);
                }
                break;
        }
        currIndex = index;
        animation.setFillAfter(true);// true表示图片停在动画结束位置
        animation.setDuration(300); //设置动画时间为300毫秒
        img_cursor.startAnimation(animation);//开始动画
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }
}

使用tabLayout实现viewPager+Fragment

<android.support.design.widget.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        <!-- 下方滚动的下划线颜色  -->
        app:tabIndicatorColor="#33aa22"
        <!-- 下方指示条的高度  -->
        app:tabIndicatorHeight="5dp"
        <!-- tab被选中后,文字的颜色  -->
        app:tabSelectedTextColor="#33aa22"
        <!--可以改变tab中的字体的大小-->
        app:tabTextAppearance="@style/App_Theme"
        <!-- tab中字体的颜色  -->
        app:tabTextColor="#33aa22"
 <!-- tab中设置横向scroll  -->
 app:tabMode="scrollable"
/>

mTabLayout.addTab(mTabLayout.newTab().setText(“标题字符串”);
设置适配器(适配器中必须重写这一步,不然标题不会显示出来)

//ViewPager与TabLayout绑定后,这里获取到PageTitle就是Tab的Text
@Override
public CharSequence getPageTitle(int position) {
    return listTitles.get(position);
}

mTabLayout.setupWithViewPager(mViewPager);
mTabLayout.setTabsFromPagerAdapter(mAdapter);

MainActivity:

package activity.lijintao.bawei.com.tablayouttest;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TabLayout mTabLayout;
    private ViewPager mViewPager;

    private LayoutInflater mInflater;
    private List<String> mTitleList = new ArrayList<>();//页卡标题集合
    private View view1, view2, view3, view4, view5;//页卡视图
    private List<View> mViewList = new ArrayList<>();//页卡视图集合
    private List<String> listTitles;
    private List<Fragment> fragments;
    private List<TextView> listTextViews;

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mViewPager = (ViewPager) findViewById(R.id.vp_view);
        mTabLayout = (TabLayout) findViewById(R.id.tabs);

        initData();



    }
    private void initData() {
        listTitles = new ArrayList<>();
        fragments = new ArrayList<>();
        listTextViews = new ArrayList<>();

        listTitles.add("推荐");
        listTitles.add("热点");
        listTitles.add("视频");
        listTitles.add("北京");
        listTitles.add("社会");
        listTitles.add("娱乐");
        listTitles.add("问答");
        listTitles.add("图片");
        listTitles.add("科技");
        listTitles.add("汽车");
        listTitles.add("体育");
        listTitles.add("财经");
        listTitles.add("军事");
        listTitles.add("国际");
        for (int i = 0; i < listTitles.size(); i++) {
            ContentFragment fragment = ContentFragment.newInstance(listTitles.get(i));
            fragments.add(fragment);

        }
        //mTabLayout.setTabMode(TabLayout.SCROLL_AXIS_HORIZONTAL);//设置tab模式,当前为系统默认模式
        for (int i=0;i<listTitles.size();i++){
            mTabLayout.addTab(mTabLayout.newTab().setText(listTitles.get(i)));//添加tab选项
        }

        FragmentPagerAdapter mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
            //ViewPager与TabLayout绑定后,这里获取到PageTitle就是Tab的Text
            @Override
            public CharSequence getPageTitle(int position) {
                return listTitles.get(position);
            }
        };
        mViewPager.setAdapter(mAdapter);

        mTabLayout.setupWithViewPager(mViewPager);//将TabLayout和ViewPager关联起来。
        mTabLayout.setTabsFromPagerAdapter(mAdapter);//给Tabs设置适配器

    }
}

Fragment代码:

   package activity.lijintao.bawei.com.tablayouttest;
    
    import android.graphics.Color;
    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;
    
    /**
     * 
     * date:2017/6/7
     */
    
    
    public class ContentFragment extends Fragment {
        private View view;
        private static final String KEY = "title";
        private TextView tvContent;
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
            view = inflater.inflate(R.layout.contentfragment,container,false);
            tvContent = (TextView) view.findViewById(R.id.tv_content);
            String string = getArguments().getString(KEY);
            tvContent.setText(string);
            tvContent.setTextColor(Color.BLUE);
            tvContent.setTextSize(30);
            return view;
        }
    
        /**
         * fragment静态传值
         */
        public static ContentFragment newInstance(String str){
            ContentFragment fragment = new ContentFragment();
            Bundle bundle = new Bundle();
            bundle.putString(KEY,str);
            fragment.setArguments(bundle);
    
            return fragment;
        }
    }

activity_main.xml

<?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/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabIndicatorColor="#F00"
        app:tabSelectedTextColor="#F00"
        app:tabTextColor="#1d1c1d"
        android:background="#f0F"
        app:tabMode="scrollable"

        >

        </android.support.design.widget.TabLayout>



    <!--可滑动的布局内容-->
    <android.support.v4.view.ViewPager
        android:id="@+id/vp_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

contentfragment.xml

<?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">

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        />
</LinearLayout>

猜你喜欢

转载自blog.csdn.net/xdy1120/article/details/90074006