使用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的圖片(就是這個小藍點)

基本上就是這些了。


發佈了41 篇原創文章 · 獲贊 9 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章