下面我们介绍下ViewPaget和Fragment的结合,四个xml布局不变直接看ManiActivity和MyFragment;
package com.example.android_viewpager_1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MyFragment extends Fragment {
/*
* 初始化fragment对象的视图
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int layout=getArguments().getInt("layout");
int position=getArguments().getInt("position");
View view=inflater.inflate(layout, null);
return view;
}
}
package com.example.android_viewpager_1;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
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.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity {
private ViewPager vp;
private List<View> views;
private int[] layoutID = { R.layout.vp_one, R.layout.vp_three,
R.layout.vp_two };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vp = (ViewPager) findViewById(R.id.vp);
MyAdapter adapter=new MyAdapter(getSupportFragmentManager());
vp.setOffscreenPageLimit(3);
vp.setAdapter(adapter);
}
// 继承自FragmentPagerAdapter,表示把Fragment放到ViewPager中。
// MyFragment长什么样子由适配器决定
private class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public Fragment getItem(int position) {
Log.i("zhangxin", "getItem():"+position);
MyFragment mf = new MyFragment();
Bundle bundle = new Bundle();
bundle.putInt("layout", layoutID[position]);
bundle.putInt("position", position);
mf.setArguments(bundle);
return mf;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return layoutID.length;
}
}
}