欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android使用ViewPager用代码实现图片轮播效果

程序员文章站 2022-04-12 20:15:58
1.activity_main.xml文件中 2.mainactivity.java文件中 package com.t20.viewpagerdemo;...

1.activity_main.xml文件中



    
    

2.mainactivity.java文件中

package com.t20.viewpagerdemo;

import java.util.arraylist;
import java.util.list;

import android.os.bundle;
import android.support.v4.view.pageradapter;
import android.support.v4.view.viewpager;
import android.view.view;
import android.view.viewgroup;
import android.widget.imageview;
import android.widget.imageview.scaletype;
import android.app.activity;

public class mainactivity extends activity {

	private viewpager vp;
	private myadapter myadapter;
	private list imglist;
	// 获取到图片
	private integer[] img = { r.drawable.pic1, r.drawable.pic2,
			r.drawable.pic3, r.drawable.pic4 };

	@override
	protected void oncreate(bundle savedinstancestate) {
		super.oncreate(savedinstancestate);
		setcontentview(r.layout.activity_main);
		vp = (viewpager) findviewbyid(r.id.vp);

		imglist = new arraylist();

		// 将图片放到集合中
		for (int i = 0; i < img.length; i++) {
			imageview iv = new imageview(this);
			iv.setimageresource(img[i]);
			// 将图片全屏显示
			iv.setscaletype(scaletype.fit_xy);
			imglist.add(iv);
		}

		// 进行适配
		myadapter = new myadapter();
		vp.setadapter(myadapter);
	}

	/**
	 * 自定义适配器
	 * 
	 * @author administrator
	 * 
	 */
	class myadapter extends pageradapter {

		@override
		public int getcount() {
			// todo auto-generated method stub
			return imglist.size();
		}

		@override
		public boolean isviewfromobject(view view, object obj) {
			// todo auto-generated method stub
			return view == obj;
		}

		/**
		 * 实例化视图内容(创建要显示的内容)
		 */
		@override
		public object instantiateitem(viewgroup container, int position) {
			// todo auto-generated method stub
			container.addview(imglist.get(position));
			return imglist.get(position);
		}

		/**
		 * 销毁视图内容
		 */
		@override
		public void destroyitem(viewgroup container, int position, object object) {
			// todo auto-generated method stub
			container.removeview((view) object);
		}
	}
}