fragment+viewpager

package com.yyc.day04_fragmentviewpager;

import java.util.ArrayList;

import com.yyc.day04_fragmentviewpager.frag.Frag01;
import com.yyc.day04_fragmentviewpager.frag.Frag02;
import com.yyc.day04_fragmentviewpager.frag.Frag03;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class MainActivity extends ActionBarActivity {

	private ViewPager pager;
	private RadioGroup radioGroup;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		pager = (ViewPager) findViewById(R.id.pager);
		radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
		//默认第一个选中
		radioGroup.check(radioGroup.getChildAt(0).getId());
		
		final ArrayList list = new ArrayList();
		Frag01 frag01 = new Frag01();
		Frag02 frag02 = new Frag02();
		Frag03 frag03 = new Frag03();
		list.add(frag01);
		list.add(frag02);
		list.add(frag03);
		
		//设置适配器
		pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
			
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return list.size();
			}
			
			@Override
			public Fragment getItem(int arg0) {
				// TODO Auto-generated method stub
				return list.get(arg0);
			}
		});
		//设施页面监听
		pager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				radioGroup.check(radioGroup.getChildAt(arg0).getId());
			}
			
			@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
				
			}
		});
		//设置页面点击监听
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch (checkedId) {
				case R.id.radio0:
					pager.setCurrentItem(0);
					break;
				case R.id.radio1:
					pager.setCurrentItem(1);
					break;
				case R.id.radio2:
					pager.setCurrentItem(2);
					break;

				default:
					break;
				}
			}
		});
	}
}

 

你可能感兴趣的:(fragment+viewpager)