Viewpager和Fragement实现翻页

新建类,继承fragement,在里面重写oncreateview(),里面返回要呈现的view视图。

public class FragementFirst extends Fragment implements OnClickListener {
	private Button btn;
	private TextView tv;
	private View view;

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

	public void init() {
		btn = (Button) view.findViewById(R.id.button1);
		tv = (TextView) view.findViewById(R.id.textView1);
		btn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == btn) {
			tv.setText("click");
		}
	}
}

如果要添加事件,就实现onclick接口,跟活动的操作差不多。

活动类:

public class MainActivity extends FragmentActivity {
	private ViewPager viewpager;
	private FramPagerAdap pageradapter;

	private FragementFirst framfirst;
	private FragementSecond framsecond;
	private FragementThird framthird;
	// 页面列表
	private List framlist = new ArrayList();
	// 标题列表
	private List<String> titlelist = new ArrayList<String>();

	// 设置标题的属性
	private PagerTitleStrip pagestrip;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.acy_main);
		init();
	}

	public void init() {
		viewpager = (ViewPager) findViewById(R.id.viewpager);
		// 加入页面
		framfirst = new FragementFirst();
		framsecond = new FragementSecond();
		framthird = new FragementThird();
		framlist.add(framfirst);
		framlist.add(framsecond);
		framlist.add(framthird);
		// 加入标题
		titlelist.add("第一页");
		titlelist.add("第二页");
		titlelist.add("第二页");

		pageradapter = new FramPagerAdap(getSupportFragmentManager(), framlist,
				titlelist);
		viewpager.setAdapter(pageradapter);

	}

	@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;
	}

}

在活动中,将fragement加载进入。

 适配器:

public class FramPagerAdap extends FragmentPagerAdapter{
	private List<Fragment> framlist;
	private List<String> titlelist;

	public FramPagerAdap(FragmentManager fm, List<Fragment> framlist,
			List<String> titlelist) {
		super(fm);
		// TODO Auto-generated constructor stub
		this.framlist = framlist;
		this.titlelist = titlelist;
	}

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

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

	@Override
	public CharSequence getPageTitle(int position) {
		// TODO Auto-generated method stub
		return titlelist.get(position);
	}

}

活动的xml:

<RelativeLayout 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.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <android.support.v4.view.PagerTitleStrip
            android:id="@+id/pagertitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </android.support.v4.view.ViewPager>

</RelativeLayout>

fragement xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="TextView1" />

</RelativeLayout>

注意:

1.跳转到其他活动:使用getactivity 来获得当前活动的实例。

在fragement中调用实例:

@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		if (v == btn) {
			//跳转到登录界面
			intent = new Intent(getActivity(), LoginActivity.class);
			startActivity(intent);
		}
	}

注意:

1.监听滑动到每页,监听应该对viewpager监听,而不是适配器,否则不起作用。

viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			// 当选中某一页
			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				Log.e("***", ";" + position);
			}

			@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

			}
		});

2.当有时候,可能会发生Fragment错位的现象,这是因为在每次滑动时,getItem()中都是相同的碎片的时候,会进行替换。我们来看下FragmentPagerAdapter源码中实例化方法:

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		if (mCurTransaction == null) {
			//FragmentTransaction 对象初始化
			mCurTransaction = mFragmentManager.beginTransaction();
		}

		final long itemId = getItemId(position);

		// Do we already have this fragment?
		String name = makeFragmentName(container.getId(), itemId);
		Fragment fragment = mFragmentManager.findFragmentByTag(name);
		
		//当找到相同id的碎片 attack()重新粘上碎片.否则,将新的碎片加载进去。
		if (fragment != null) {
			if (DEBUG)
				Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
			mCurTransaction.attach(fragment);
		} else {
			fragment = getItem(position);
			if (DEBUG)
				Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
			mCurTransaction.add(container.getId(), fragment,
					makeFragmentName(container.getId(), itemId));
		}
		if (fragment != mCurrentPrimaryItem) {
			fragment.setMenuVisibility(false);
			fragment.setUserVisibleHint(false);
		}

		return fragment;
	}

当你同时沾上两片一样的碎片的时候。有可能会导致错位,当然也有可能不会(就是相互覆盖得很好)。

我们为了避免这种情况,在getItem()中,添加处理就可以了。

//当碎片页以前没加载进去过
		if (null == fManager.findFragmentById(position)) {
			return fragment;
		}
		return fManager.findFragmentById(position);




你可能感兴趣的:(viewpager,Fragement)