安卓日记——ViewPager与RadioGroup关联

首先说viewpager吧

他是一种特殊的控件在layout里必须写成android.support.v4.view.ViewPager

<android.support.v4.view.ViewPager
	    android:id="@+id/viewpager"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:layout_gravity="center"
	    android:layout_weight="9">
	  
	    
	</android.support.v4.view.ViewPager>

首先在mainactivity里实例化一个viewpager

viewpager需要用到不同页面的view

最好用一个List装

新建若干个layout

inflate成view

然后添加进list

然后要set一个继承自PagerAdapter的adapter

viewPager.setAdapter(new MyAdapter());

class MyAdapter extends PagerAdapter {

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

    	@Override
    	public void destroyItem(ViewGroup container, int position, Object object) {
    		((ViewPager)container).removeView(list.get(position));
    	}
    	
    	
    	@Override
    	public Object instantiateItem(ViewGroup container, int position) {
    		((ViewPager)container).addView(list.get(position));   		
    		return list.get(position);//显示返回的view
    	}
    	@Override
    	public boolean isViewFromObject(View arg0, Object arg1) {
    		// TODO Auto-generated method stub
    		return arg0==arg1;//判断是否关联
    	}

    }

然后就是新建RadioGroup

实例化RadioGroup和里面的Radiobutton

然后就是设置一个勾选改变的listener(哪个选中就跳转到哪个页面)

radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				switch (arg1) {
				case R.id.btn1:
					viewPager.setCurrentItem(0);
					break;
				case R.id.btn2:
					viewPager.setCurrentItem(1);
					break;
				case R.id.btn3:
					viewPager.setCurrentItem(2);
					break;
				}
				
			}
		});

然后viewpager也要设置一个page改变的listener

在listener里改变选中的radiobutton

viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				switch (arg0) {
				case 0:
					btn1.setChecked(true);
					break;
				case 1:
					btn2.setChecked(true);
					break;
				case 2:
					btn3.setChecked(true);
					break;

			
				}
				
			}







你可能感兴趣的:(安卓日记——ViewPager与RadioGroup关联)