1. 程式人生 > >ViewPager + Fragment實現滑動標籤頁

ViewPager + Fragment實現滑動標籤頁

ViewPager 結合Fragment實現一個Activity裡包含多個可滑動的標籤頁,每個標籤頁可以有獨立的佈局及響應。

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        
        
        <TextView 
            android:id="@+id/tv_guid1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1.0"
            android:gravity="center"
            android:text="特性1"
            android:textSize="18sp"/>
        <TextView  
            android:id="@+id/tv_guid2"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_weight="1.0"  
            android:gravity="center"  
            android:text="特性2"   
            android:textSize="18sp"/>  
  
        <TextView  
            android:id="@+id/tv_guid3"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_weight="1.0"  
            android:gravity="center"  
            android:text="特性3 "   
            android:textSize="18sp"/>  
  
        <TextView  
            android:id="@+id/tv_guid4"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_weight="1.0"  
            android:gravity="center"  
            android:text="特性4"   
            android:textSize="18sp"/>
    </LinearLayout>

    <ImageView 
        android:id="@+id/cursor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="matrix"
        android:src="@drawable/cursor"/>
    
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:flipInterval="30"
        android:persistentDrawingCache="animation"/>
</LinearLayout>


MainActivity.java

package com.example.viewpagernfragment;

import java.util.ArrayList;

import android.graphics.BitmapFactory;
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.DisplayMetrics;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
	private ViewPager mPager;
	private ArrayList<Fragment> fragmentList;
	private ImageView image;
	private TextView view1, view2, view3, view4;
	private int currIndex;//當前頁卡編號
	private int bmpW;//橫線圖片寬度
	private int offset;//圖片移動的偏移量

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		InitTextView();
		InitImage();
		InitViewPager();
	}
	
	
	/*
	 * 初始化標籤名
	 */
	public void InitTextView(){
		view1 = (TextView)findViewById(R.id.tv_guid1);
		view2 = (TextView)findViewById(R.id.tv_guid2);
		view3 = (TextView)findViewById(R.id.tv_guid3);
		view4 = (TextView)findViewById(R.id.tv_guid4);
		
		view1.setOnClickListener(new txListener(0));
		view2.setOnClickListener(new txListener(1));
		view3.setOnClickListener(new txListener(2));
		view4.setOnClickListener(new txListener(3));
	}
	
	
	public class txListener implements View.OnClickListener{
		private int index=0;
		
		public txListener(int i) {
			index =i;
		}
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			mPager.setCurrentItem(index);
		}
	}
	
	
	/*
	 * 初始化圖片的位移畫素
	 */
	public void InitImage(){
		image = (ImageView)findViewById(R.id.cursor);
		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.cursor).getWidth();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;
		offset = (screenW/4 - bmpW)/2;
		
		//imgageview設定平移,使下劃線平移到初始位置(平移一個offset)
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		image.setImageMatrix(matrix);
	}
	
	/*
	 * 初始化ViewPager
	 */
	public void InitViewPager(){
		mPager = (ViewPager)findViewById(R.id.viewpager);
		fragmentList = new ArrayList<Fragment>();
		Fragment btFragment= new ButtonFragment();
		Fragment secondFragment = TestFragment.newInstance("this is second fragment");
		Fragment thirdFragment = TestFragment.newInstance("this is third fragment");
		Fragment fourthFragment = TestFragment.newInstance("this is fourth fragment");
		fragmentList.add(btFragment);
		fragmentList.add(secondFragment);
		fragmentList.add(thirdFragment);
		fragmentList.add(fourthFragment);
		
		//給ViewPager設定介面卡
		mPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(), fragmentList));
		mPager.setCurrentItem(0);//設定當前顯示標籤頁為第一頁
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());//頁面變化時的監聽器
	}

	
	public class MyOnPageChangeListener implements OnPageChangeListener{
		private int one = offset *2 +bmpW;//兩個相鄰頁面的偏移量
		
		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onPageScrollStateChanged(int arg0) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void onPageSelected(int arg0) {
			// TODO Auto-generated method stub
			Animation animation = new TranslateAnimation(currIndex*one,arg0*one,0,0);//平移動畫
			currIndex = arg0;
			animation.setFillAfter(true);//動畫終止時停留在最後一幀,不然會回到沒有執行前的狀態
			animation.setDuration(200);//動畫持續時間0.2秒
			image.startAnimation(animation);//是用ImageView來顯示動畫的
			int i = currIndex + 1;
			Toast.makeText(MainActivity.this, "您選擇了第"+i+"個頁卡", Toast.LENGTH_SHORT).show();
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

谷歌官方認為,ViewPager應該和Fragment一起使用時,此時ViewPager的介面卡是FragmentPagerAdapter,當你實現一個FragmentPagerAdapter,你必須至少覆蓋以下方法:

getCount()

getItem()

如果ViewPager沒有和Fragment一起,ViewPager的介面卡是PagerAdapter,它是基類提供介面卡來填充頁面ViewPager內部,當你實現一個PagerAdapter,你必須至少覆蓋以下方法:


package com.example.viewpagernfragment;

import java.util.ArrayList;

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

public class MyFragmentPagerAdapter extends FragmentPagerAdapter{
	ArrayList<Fragment> list;
	public MyFragmentPagerAdapter(FragmentManager fm,ArrayList<Fragment> list) {
		super(fm);
		this.list = list;
		
	}
	
	
	@Override
	public int getCount() {
		return list.size();
	}
	
	@Override
	public Fragment getItem(int arg0) {
		return list.get(arg0);
	}
	
	
	
	
}

package com.example.viewpagernfragment;

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

public class ButtonFragment extends Fragment{
	Button myButton;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.guide_1, container, false);//關聯佈局檔案
		
		myButton = (Button)rootView.findViewById(R.id.mybutton);//根據rootView找到button
		
		//設定按鍵監聽事件
		myButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(ButtonFragment.this.getActivity(), "button is click!", Toast.LENGTH_SHORT).show();
			}
		});
		
		
		return rootView;
	}
}

package com.example.viewpagernfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TestFragment extends Fragment {
    private static final String TAG = "TestFragment";
    private String hello;// = "hello android";
    private String defaultHello = "default value";

    static TestFragment newInstance(String s) {
        TestFragment newFragment = new TestFragment();
        Bundle bundle = new Bundle();
        bundle.putString("hello", s);
        newFragment.setArguments(bundle);
        
        //bundle還可以在每個標籤裡傳送資料
        
        
        return newFragment;

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        Log.d(TAG, "TestFragment-----onCreateView");
        Bundle args = getArguments();
        hello = args != null ? args.getString("hello") : defaultHello;
        View view = inflater.inflate(R.layout.guide_2, container, false);
        TextView viewhello = (TextView) view.findViewById(R.id.tv);
        viewhello.setText(hello);
        return view;

    }

   

}

<?xml version="1.0" encoding="UTF-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    android:background="#ff0000ff" >  
    
    <Button 
        android:id="@+id/mybutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hit me"
        android:gravity="center"/>
</RelativeLayout>  

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#158684" >


    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</RelativeLayout>