Android 导航条效果实现(四) ViewPager+自定义导航条

ViewPager+自定义导航条实现导航效果



效果说明:

  • 自定义导航条;
  • 导航条固定位置,选项卡按比例显示;
  • 选项卡下方有一个指示器,指示当前页面的位置。



参考代码
自定义的选项卡布局:
TabsView.java

package com.noonecode.viewpagertabsdemo;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 一个简单的Tabs选项卡视图
 * 
 * @author noonecode
 *
 */
public class TabsView extends LinearLayout {

    private int mSelectedColor = 0xffff0000;// 选中的字体颜色
    private int mNotSelectedColor = ((mSelectedColor >>> 25) << 24) | (mSelectedColor & 0x00ffffff);// 未选中的字体颜色

    private int mIndicatorColor = 0xff0000ff;// 指示器的颜色

    private LinearLayout mTabsContainer;// 放置tab的容器
    private View mIndicator, mBottomLine;// 指示器和底部横线

    private OnTabsItemClickListener listener;

    public TabsView(Context context) {
        this(context, null);
    }

    public TabsView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TabsView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(VERTICAL);
        // 初始化容器
        mTabsContainer = new LinearLayout(getContext());
        mTabsContainer.setOrientation(HORIZONTAL);
        mTabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        addView(mTabsContainer);
        // 初始化指示器
        mIndicator = new View(getContext());
        mIndicator.setBackgroundColor(mIndicatorColor);
        mIndicator.setLayoutParams(new LayoutParams(300, 8));// 先任意设置宽度
        addView(mIndicator);
        // 初始化底部横线
        mBottomLine = new View(getContext());
        mBottomLine.setBackgroundColor(mIndicatorColor);
        mBottomLine.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 2));
        addView(mBottomLine);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        resetIndicator();
    }

    /**
     * 重新设置指示器
     */
    private void resetIndicator() {
        int childCount = mTabsContainer.getChildCount();
        ViewGroup.LayoutParams layoutParams = mIndicator.getLayoutParams();
        if (childCount <= 0) {
            layoutParams.width = 0;
        } else {
            layoutParams.width = getWidth() / childCount;
        }
        mIndicator.setLayoutParams(layoutParams);
        // mIndicator.setX(0f);
    }

    /**
     * 设置选项卡
     * 
     * @param titles
     */
    public void setTabs(String... titles) {
        mTabsContainer.removeAllViews();
        if (titles != null) {
            for (int i = 0; i < titles.length; i++) {
                TextView textView = new TextView(getContext());
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
                // textView.setTextColor(mNotSelectedColor);
                textView.setText(titles[i]);
                textView.setClickable(true);
                textView.setPadding(0, 10, 0, 10);
                textView.setGravity(Gravity.CENTER);
                textView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f));
                textView.setTag(i);
                textView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        int position = (Integer) v.getTag();
                        setCurrentTab(position, true);
                        if (listener != null) {
                            listener.onClick(v, position);
                        }
                    }
                });
                mTabsContainer.addView(textView);
            }
            // 初始化,默认选中第一个
            setCurrentTab(0, false);
            // 设置指示器
            post(new Runnable() {
                @Override
                public void run() {
                    // 设置指示器
                    resetIndicator();
                }
            });
        }
    }

    /**
     * 设置当前的tab
     * 
     * @param position
     */
    public void setCurrentTab(int position, boolean anim) {
        int childCount = mTabsContainer.getChildCount();
        if (position < 0 || position >= childCount) {
            return;
        }
        // 设置每个tab的状态
        for (int i = 0; i < childCount; i++) {
            TextView childView = (TextView) mTabsContainer.getChildAt(i);
            if (i == position) {
                childView.setTextColor(mSelectedColor);
            } else {
                childView.setTextColor(mNotSelectedColor);
            }
        }
        // 指示器的移动
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mIndicator, "x", position * mIndicator.getWidth());
        if (anim) {
            objectAnimator.setDuration(200).start();
        } else {
            objectAnimator.setDuration(0).start();
        }
    }

    /**
     * Tabs点击的监听事件
     * 
     * @param listener
     */
    public void setOnTabsItemClickListener(OnTabsItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnTabsItemClickListener {
        public void onClick(View view, int position);
    }
}


在布局中使用TabsView
activity_main.java

"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.noonecode.viewpagertabsdemo.MainActivity" >

    <com.noonecode.viewpagertabsdemo.TabsView
        android:id="@+id/tabslayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    .support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />



MainActivity.java

package com.noonecode.viewpagertabsdemo;

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

import com.noonecode.viewpagertabsdemo.TabsView.OnTabsItemClickListener;

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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;

public class MainActivity extends FragmentActivity {

    private ViewPager mViewPager;
    private TabsView mTabs;

    private List fragments;
    private MyAdapter adapter;

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

        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mTabs = (TabsView) findViewById(R.id.tabslayout);

        initData();
    }

    private void initData() {
        fragments = new ArrayList();
        fragments.add(new FragmentPage1());
        fragments.add(new FragmentPage2());
        fragments.add(new FragmentPage3());
        fragments.add(new FragmentPage4());
        //设置适配器
        adapter = new MyAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(adapter);
        //初始化选项卡
        mTabs.setTabs("选项卡1","选项卡2","选项卡3","选项卡4");
        mTabs.setOnTabsItemClickListener(new OnTabsItemClickListener() {

            @Override
            public void onClick(View view, int position) {
                mViewPager.setCurrentItem(position, true);
            }
        });
        //
        mViewPager.addOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                mTabs.setCurrentTab(position, true);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    class MyAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

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

每个Fragment都是简单的Fragment,只有一个TextView,不再赘述。



运行效果:
Android 导航条效果实现(四) ViewPager+自定义导航条_第1张图片


注意

  • 这里简单的自定义了一个视图TabsView的好处在于,不需要在布局中写每个选项卡的布局,每个选项卡都是根据设置的标题自动生成的。使用起来比较方便。




(完毕)

导航:
Android 导航条效果实现(一) TabActivity+TabHost
http://blog.csdn.net/qq_33425116/article/details/52573967

Android 导航条效果实现(二) FragmentTabHost
http://blog.csdn.net/qq_33425116/article/details/52575811

Android 导航条效果实现(三) ViewPager+PagerTabStrip
http://blog.csdn.net/qq_33425116/article/details/52577570

Android 导航条效果实现(四) ViewPager+自定义导航条
http://blog.csdn.net/qq_33425116/article/details/52584282

Android 导航条效果实现(五) ActionBar+Fragment
http://blog.csdn.net/qq_33425116/article/details/52587635

Android 导航条效果实现(六) TabLayout+ViewPager+Fragment
http://blog.csdn.net/qq_33425116/article/details/52599818

你可能感兴趣的:(Android,android,viewpager,导航,tab)