Android ViewPager使用方法


如图,android中使用ViewPager可以实现多个页面滑动效果、


public class TvControlActivity extends Activity {
	private TvControlActivity tvControlActivity = this;
	// 需要滑动的页卡
	private View view1;
	private View view2;
	private View view3;
	private ArrayList<View> views;
	// 多页面滑动切换
	private ViewPager viewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tv_control);
		viewPager = (ViewPager) findViewById(R.id.main_viewpager);
		viewPager.setOnPageChangeListener(null);
		initView();
		/**
		 * 这是重写PagerAdapter的一个方法,我们还可以这样做
		 */
		PagerAdapter paAdapter = new PagerAdapter() {

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return views.size();
			}
			//销毁
			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object) {
				// TODO Auto-generated method stub
				container.removeView(views.get(position));
			}
//			@Override
//			public void destroyItem(View container, int position, Object object) {
//				// TODO Auto-generated method stub
//				((ViewPager) container).removeView(views.get(position));
//
//			}

			@Override
			public int getItemPosition(Object object) {
				// TODO Auto-generated method stub
				return super.getItemPosition(object);
			}
			//实例化
			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				// TODO Auto-generated method stub
				container.addView(views.get(position));
				return views.get(position);
			}
//			@Override
//			public Object instantiateItem(View container, int position) {
//				// TODO Auto-generated method stub
//				((ViewPager) container).addView(views.get(position));
//				return views.get(position);
//			}
		};
		viewPager.setAdapter(paAdapter);
	}
	/**
	 * 加载要显示的页卡
	 */
	private void initView() {
		// TODO Auto-generated method stub
		LayoutInflater inflater = getLayoutInflater().from(this);
		view1 = inflater.inflate(R.layout.tv_control, null);
		view2 = inflater.inflate(R.layout.tv_control_number, null);
		// 将要分页显示的View装入数组中
		views = new ArrayList<View>();
		views.add(view1);
		views.add(view2);
	}
}
在实现adapter的时候一定要重写以下四个方法,其他方法的话也可以重写

instantiateItem(ViewGroup container, int position)
getItemPosition(Object object)
destroyItem(ViewGroup container, int position,Object object)
isViewFromObject(View arg0, Object arg1)


需要注意的是布局文件中需要这样写
<android.support.v4.view.ViewPager  注意这个组件是用来显示左右滑动的界面的,如果不加载xml布局文件,他是不会显示内容的
        android:id="@+id/main_viewpager"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" >
    </android.support.v4.view.ViewPager>



Android ViewPager使用方法,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。