使用Viewpager 和 Fragment实现顶部导航

先看下效果


不是特别清楚,凑活一下吧。上代码。

先来看一下都需要那些文件:


右边是布局文件,左边是java文件

一 布局文件。

activity_main.xml

<LinearLayout 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"
    android:orientation="vertical"
    >

	<include layout="@layout/slide_tab_top"/>   
    
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         >

        <ImageView
            android:id="@+id/cursor"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitXY"
            android:src="@drawable/main_underline" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_weight="1.0"
        android:background="#ffffff"
        android:flipInterval="30"
        android:persistentDrawingCache="animation" />

</LinearLayout>

slide_tab_top.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  	android:id="@+id/slide_tab"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/text1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:text="沐浴"
            android:textColor="@color/text_color"
            android:textSize="16sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/text2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:text="按摩"
            android:textColor="@color/text_color"
            android:textSize="16sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/text3"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:text="足疗"
            android:textColor="@color/text_color"
            android:textSize="16sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/text4"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:text="SPA"
            android:textColor="@color/text_color"
            android:textSize="16sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/text5"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:text="娱乐"
            android:textColor="@color/text_color"
            android:textSize="16sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/text6"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:text="度假"
            android:textColor="@color/text_color"
            android:textSize="16sp" />
    </LinearLayout>

</LinearLayout>

fragment1.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"
    android:orientation="vertical" 
    android:gravity="center">
    
    <TextView android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="first_fragment"/>

</LinearLayout>

fragment2.xml-fragment6.xml差不多,就不贴出了


二、java文件

MainActivity.java

package com.lql.tabbtndemo;

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

import com.lql.tabbtndemo.util.ScreenUtils;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends FragmentActivity implements OnClickListener{

	private static String TAG = "MainActivity";
	
	private ViewPager viewPager;

	/**
	 * 指示器图片
	 */
	private ImageView indicatorImg;

	/**
	 * 顶部的几个tab导航卡
	 */
	private TextView tab1, tab2, tab3, tab4, tab5, tab6;

	private int offset = 0;// 动画图片偏移量
	private int currentIndex = 0;// 当前页卡编号
	private int indicatorImgWidth;// 动画图片宽度
	/**
	 * Fragment的集合
	 */
	private List<Fragment> mFragments = new ArrayList<Fragment>();
	/**
	 * Fragment的数据适配器
	 */
	private MyFragmentAdapter mAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		init();
	}
	
	
	private void init() {
		// TODO Auto-generated method stub
		initIndicator();
		initTabTextView();
		initViewPager();
	}


	/**
	 * 对游标指示器初始化
	 */
	private void initIndicator() {
		// TODO Auto-generated method stub
		
		indicatorImg = (ImageView)findViewById(R.id.cursor);
		/**
		 * 根据每个屏幕宽度,计算游标的长
		 */
		int indicatorWidth = ScreenUtils.getScreenWidth(this) / 6;
		LayoutParams params = indicatorImg.getLayoutParams();
		params.width = indicatorWidth;
		indicatorImg.setLayoutParams(params);
		
		//图片宽度
		indicatorImgWidth = BitmapFactory.decodeResource(getResources(), R.drawable.main_underline).getWidth();
		//偏移量
		offset = indicatorWidth;
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		indicatorImg.setImageMatrix(matrix);// 设置动画初始位置
		
	}


	/**
	 * 初始导航卡
	 */
	private void initTabTextView() {
		// TODO Auto-generated method stub
		tab1 = (TextView)findViewById(R.id.text1);
		tab2 = (TextView)findViewById(R.id.text2);
		tab3 = (TextView)findViewById(R.id.text3);
		tab4 = (TextView)findViewById(R.id.text4);
		tab5 = (TextView)findViewById(R.id.text5);
		tab6 = (TextView)findViewById(R.id.text6);
		
		tab1.setOnClickListener(new MyTabOnClickListener(0));
		tab2.setOnClickListener(new MyTabOnClickListener(1));
		tab3.setOnClickListener(new MyTabOnClickListener(2));
		tab4.setOnClickListener(new MyTabOnClickListener(3));
		tab5.setOnClickListener(new MyTabOnClickListener(4));
		tab6.setOnClickListener(new MyTabOnClickListener(5));
	}

	/**
	 * 点击导航选项卡时,就选中相应的Fragment
	 * @author Administrator
	 *
	 */
	private class MyTabOnClickListener implements OnClickListener{

		int index  = 0;
		public MyTabOnClickListener(int index){
			this.index = index;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			viewPager.setCurrentItem(index);
		}
		
	}

	@SuppressWarnings("deprecation")
	private void initViewPager() {
		// TODO Auto-generated method stub
		viewPager = (ViewPager)findViewById(R.id.viewpager);
		Fragment1 fragment1 = new Fragment1();
		Fragment2 fragment2 = new Fragment2();
		Fragment3 fragment3 = new Fragment3();
		Fragment4 fragment4 = new Fragment4();
		Fragment5 fragment5 = new Fragment5();
		Fragment6 fragment6 = new Fragment6();
		
		mFragments.add(fragment1);
		mFragments.add(fragment2);
		mFragments.add(fragment3);
		mFragments.add(fragment4);
		mFragments.add(fragment5);
		mFragments.add(fragment6);
		
		mAdapter = new MyFragmentAdapter(getSupportFragmentManager(), mFragments);
		viewPager.setAdapter(mAdapter);
		viewPager.setCurrentItem(0);
		tab1.setTextColor(Color.BLUE);
		viewPager.setOffscreenPageLimit(5);// 设置缓存页面,6个页面缓存5个,这样每次就不用调用onCreateView方法
		viewPager.setOnPageChangeListener(new MyPageChangeListener());//设置Page页改变时的监听事件
	}
	
	private class MyPageChangeListener implements OnPageChangeListener{

		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onPageSelected(int index) {
			// TODO Auto-generated method stub
			
			int one = offset;
			Log.d(TAG,"one:" + one+ "------------>offset:"+offset);
			resetTabTextView();
			switch (index) {
			case 0:
				tab1.setTextColor(Color.BLUE);
				break;
			case 1:
				tab2.setTextColor(Color.BLUE);
				break;
			case 2:
				tab3.setTextColor(Color.BLUE);
				break;
			case 3:
				tab4.setTextColor(Color.BLUE);
				break;
			case 4:
				tab5.setTextColor(Color.BLUE);
				break;
			case 5:
				tab6.setTextColor(Color.BLUE);
				break;
			default:
				break;
			}
			/**
			 * 定义选项卡指示器的动画,做水平滑动 , X坐标从one * currentIndex 变换到 one * index
			 */
			Animation animation =new TranslateAnimation(one * currentIndex, one * index, 0, 0);
			currentIndex = index;//改变当前索引值
			animation.setFillAfter(true);//设置为True后,图片停在动画结束的位置
			animation.setDuration(300);//动画持续时长 300毫秒
			indicatorImg.startAnimation(animation);//启动动画
		}

		
	}
	
	private void resetTabTextView() {
		// TODO Auto-generated method stub
		tab1.setTextColor(Color.BLACK);
		tab2.setTextColor(Color.BLACK);
		tab3.setTextColor(Color.BLACK);
		tab4.setTextColor(Color.BLACK);
		tab5.setTextColor(Color.BLACK);
		tab6.setTextColor(Color.BLACK);
	}


	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}

}

<pre name="code" class="java">MyFragmentAdapter.java

 

package com.lql.tabbtndemo;

import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;


/**
 * Fragmnet的适配器
 * @author Administrator
 *
 */
public class MyFragmentAdapter extends FragmentPagerAdapter {

	private List<Fragment> mFragments;
	
	public MyFragmentAdapter(FragmentManager fm , List<Fragment> fragments) {
		super(fm);
		this.mFragments = fragments;
		// TODO Auto-generated constructor stub
	}

	@Override
	public Fragment getItem(int arg0) {
		// TODO Auto-generated method stub
		return mFragments.get(arg0);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return mFragments.size();
	}

}


Fragment1.java

package com.lql.tabbtndemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment1, container, false);
	}
	
}

Fragment2-Fragment6.java与Fragment1.java类似


还有一个获取屏幕宽度的工具类ScreenUtil.java

package com.lql.tabbtndemo.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

/**
 * 鑾峰緱灞忓箷鐩稿叧鐨勮緟鍔╃�?
 * 
 * @author zhy
 * 
 */
public class ScreenUtils
{
	private ScreenUtils()
	{
		/* cannot be instantiated */
		throw new UnsupportedOperationException("cannot be instantiated");
	}

	/**
	 * 鑾峰緱灞忓箷楂樺�?
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenWidth(Context context)
	{
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return outMetrics.widthPixels;
	}

	/**
	 * 鑾峰緱灞忓箷瀹藉�?
	 * 
	 * @param context
	 * @return
	 */
	public static int getScreenHeight(Context context)
	{
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics outMetrics = new DisplayMetrics();
		wm.getDefaultDisplay().getMetrics(outMetrics);
		return outMetrics.heightPixels;
	}

	/**
	 * 鑾峰緱鐘舵�佹爮鐨勯珮搴�?
	 * 
	 * @param context
	 * @return
	 */
	public static int getStatusHeight(Context context)
	{

		int statusHeight = -1;
		try
		{
			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object object = clazz.newInstance();
			int height = Integer.parseInt(clazz.getField("status_bar_height")
					.get(object).toString());
			statusHeight = context.getResources().getDimensionPixelSize(height);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return statusHeight;
	}

	/**
	 * 鑾峰彇褰撳墠灞忓箷鎴浘锛屽寘鍚姸鎬佹�?
	 * 
	 * @param activity
	 * @return
	 */
	public static Bitmap snapShotWithStatusBar(Activity activity)
	{
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bmp = view.getDrawingCache();
		int width = getScreenWidth(activity);
		int height = getScreenHeight(activity);
		Bitmap bp = null;
		bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
		view.destroyDrawingCache();
		return bp;

	}

	/**
	 * 鑾峰彇褰撳墠灞忓箷鎴浘锛屼笉鍖呭惈鐘舵�佹�?
	 * 
	 * @param activity
	 * @return
	 */
	public static Bitmap snapShotWithoutStatusBar(Activity activity)
	{
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap bmp = view.getDrawingCache();
		Rect frame = new Rect();
		activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;

		int width = getScreenWidth(activity);
		int height = getScreenHeight(activity);
		Bitmap bp = null;
		bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
				- statusBarHeight);
		view.destroyDrawingCache();
		return bp;

	}

}

还有一张main_underline.png的图片 (就是这个小蓝点)

基本上就是这些了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值