ViewPager + Fragment实现滑动标签页

来源:互联网 发布:arcgis数据视图做表格 编辑:程序博客网 时间:2024/06/05 22:37

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;//图片移动的偏移量@Overrideprotected 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;}@Overridepublic void onClick(View v) {// TODO Auto-generated method stubmPager.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;//两个相邻页面的偏移量@Overridepublic void onPageScrolled(int arg0, float arg1, int arg2) {// TODO Auto-generated method stub}@Overridepublic void onPageScrollStateChanged(int arg0) {// TODO Auto-generated method stub}@Overridepublic void onPageSelected(int arg0) {// TODO Auto-generated method stubAnimation 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();}}@Overridepublic 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,你必须至少覆盖以下方法:

instantiateItem(ViewGroup, int)
destroyItem(ViewGroup, int, Object)
getCount()
isViewFromObject(View, Object)

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;}@Overridepublic int getCount() {return list.size();}@Overridepublic 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;@Overridepublic 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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubToast.makeText(ButtonFragment.this.getActivity(), "button is click!", Toast.LENGTH_SHORT).show();}});return rootView;}}


 

 

0 0
原创粉丝点击