轮流播放图片

xiaoxiao2021-02-28  8

布局代码:

图片工具类:

方法类:

public class ADBean { private String id; private String adName;//广告词 private String imgUrl;//网络图片资源 private int imgPath=-1;//本地图片资源 private ImageView mImageView; public ImageView getmImageView() { return mImageView; } public void setmImageView(ImageView mImageView) { this.mImageView = mImageView; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAdName() { return adName; } public void setAdName(String adName) { this.adName = adName; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } public int getImgPath() { return imgPath; } public void setImgPath(int imgPath) { this.imgPath = imgPath; }

}

配置文件:

public class TuTu implements OnItemClickListener  { public static final String TAG = "TuTu"; private ViewPager mViewPager; private TextView mTextView; private LinearLayout mLinearLayout; private MyAdapter myPagerAdapter; private int lastPoint = 0; private boolean isRunning = false; boolean stat = false; private Timer timer; private TimerTask timerTask; private List<ADBean> listADbeans; private Context mContext; private ImageUtil imageUtil; private int newPosition=0; private long delay=4000; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { int what = msg.what; if(what == 0){ if(listADbeans.size()>1){ mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1, true); } } if(what ==1){ myPagerAdapter.notifyImages(listADbeans); } }; }; public TuTu(ViewPager mViewPager,TextView mTextView,LinearLayout mLinearLayout,Context mContext,List<ADBean> listADbeans) { this.mContext = mContext; this.listADbeans = listADbeans; this.mViewPager = mViewPager; this.mTextView = mTextView; this.mLinearLayout = mLinearLayout; imageUtil = new ImageUtil(mContext); //changeViewpagerSpace(); initADViewpager(); } /** * 改变viewpager切换速度 */ private void changeViewpagerSpace() { try {            Field field = ViewPager.class.getDeclaredField("mScroller");            field.setAccessible(true);            FixedSpeedScroller scroller = new FixedSpeedScroller(mViewPager.getContext(),                    new AccelerateInterpolator());            field.set(mViewPager, scroller);            //scroller.setmDuration(200);        } catch (Exception e) {            e.printStackTrace();        } } private void initADViewpager() { for(int i = 0; i < listADbeans.size(); i++){ ImageView view = new ImageView(mContext); //view.setBackgroundResource(listADbeans.get(i).getImgPath()); // 把图片添加到列表 listADbeans.get(i).setmImageView(view); // 实例化指示点 ImageView point = new ImageView(mContext); point.setImageResource(R.drawable.point_seletor); LayoutParams params = new LayoutParams(dip2px(mContext,6), dip2px(mContext,6)); params.leftMargin = dip2px(mContext,10); point.setLayoutParams(params); // 将指示点添加到线性布局里 mLinearLayout.addView(point); // 设置第一个高亮显示 if (i == 0) { point.setEnabled(true); } else { point.setEnabled(false); } } // 设置适配器 myPagerAdapter = new MyAdapter(listADbeans); myPagerAdapter.setOnItemClickListener(this); mViewPager.setAdapter(myPagerAdapter); // 设置默认文字信息 if(listADbeans!= null && listADbeans.size()>0 && mTextView!= null){ mTextView.setText(listADbeans.get(0).getAdName()); } int midPosition = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % listADbeans.size(); if(listADbeans.size()==1){ midPosition = 0; } mViewPager.setCurrentItem(midPosition); // 设置页面改变监听 mViewPager.setOnPageChangeListener(new OnPageChangeListener() { private float mPreviousOffset = -1;        private float mPreviousPosition = -1; /** * 当某个页面被选中的时候回调 */ @Override public void onPageSelected(int position) { newPosition = position % listADbeans.size(); // 取出广告文字 String msg = listADbeans.get(position % listADbeans.size()).getAdName(); if(mTextView!=null){ mTextView.setText(msg); } // 设置对应的页面高亮 mLinearLayout.getChildAt(newPosition).setEnabled(true); // 是上次的点不显示高亮 mLinearLayout.getChildAt(lastPoint).setEnabled(false); lastPoint = newPosition; } /** * 当某个页面被滚动的时候回调 */ @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } /** * 当状态发生改变的时候回调, 静止-滚动-静止 */ @Override public void onPageScrollStateChanged(int state) { if(state ==1){ timer.cancel(); //timerTask.cancel(); stat = true; } if(state ==0){ if(stat){ startViewPager(delay); } stat = false; } } }); isRunning = true; getNetImages(); } /** * 加载网络图片 */ private void getNetImages() { for(ADBean ad:listADbeans){ String url = ad.getImgUrl(); if(url ==null || TextUtils.isEmpty(url)){ return; } String imageName = url.substring(url.lastIndexOf("/")+1, url.length()); if(!imageName.endsWith(".jpg") && !imageName.endsWith(".png")){ imageName += ".png"; } String imagePath = ImageUtil.IMAGE_PATH+imageName; if(url!= null && !TextUtils.isEmpty(url)){ imageUtil.loadImage(imageName, url, true, new ImageCallback() { @Override public void onStart(String imageUrl) { Log.i(TAG, "开始=="+imageUrl); } @Override public void onFailed(String imageUrl) { Log.i(TAG, "失败=="+imageUrl); } @Override public void loadImage(Bitmap bitmap, String imageUrl) { Log.i(TAG, imageUrl); for(ADBean bean :listADbeans){ if(imageUrl.equals(bean.getImgUrl())){ bean.getmImageView().setImageBitmap(bitmap); } } handler.sendEmptyMessage(1); } }); } } } /** * 开启轮播图 * @param delay */ public void startViewPager(long delay) { this.delay = delay; timer = new Timer(); timerTask = new TimerTask() { public void run() { handler.sendEmptyMessage(0); }; timer.schedule(timerTask, delay,delay); } public void destroyView() { if(timer!= null){ timer.cancel(); } if(timerTask!= null){ timer.cancel(); } } public class FixedSpeedScroller extends Scroller {    private int mDuration = 300;      public FixedSpeedScroller(Context context) {        super(context);    }      public FixedSpeedScroller(Context context, Interpolator interpolator) {        super(context, interpolator);    }      @Override    public void startScroll(int startX, int startY, int dx, int dy, int duration) {        // Ignore received duration, use fixed one instead        super.startScroll(startX, startY, dx, dy, mDuration);    }      @Override    public void startScroll(int startX, int startY, int dx, int dy) {        // Ignore received duration, use fixed one instead        super.startScroll(startX, startY, dx, dy, mDuration);    }      public void setmDuration(int time) {        mDuration = time;    }      public int getmDuration() {        return mDuration;    } } /**      * 根据手机的分辨率从 dip 的单位 转成为 px(像素)      */      public static int dip2px(Context context, float dpValue) {          final float scale = context.getResources().getDisplayMetrics().density;          return (int) (dpValue * scale + 0.5f);      }        /**      * 根据手机的分辨率从 px(像素) 的单位 转成为 dp      */      public static int px2dip(Context context, float pxValue) {          final float scale = context.getResources().getDisplayMetrics().density;          return (int) (pxValue / scale + 0.5f);      }    /**     * viewpager的item点击事件     */ @Override public void OnItemClick(View view, int position) { System.out.println(position+""); }

}

完整代码:

public class MainActivityTwo extends Activity{ private ViewPager ad_viewPage; /** * 显示的文字Textview */ private TextView tv_msg; /** * 添加小圆点的线性布局 */ private LinearLayout ll_dian; /** * 轮播图对象列表 */ List<ADBean> listADbeans; /** * 本地图片资源 */ private int[] ids = { R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.fore, R.drawable.five }; /** * 显示文字 */ private String[] des = { "1111111", "22222222", "3333333", "4444444444","55555555555" }; /** * 网络资源 */ private String[] urls = { "http://a.hiphotos.baidu.com/image/pic/item/0bd162d9f2d3572ce98282e18e13632762d0c3af.jpg", "http://d.hiphotos.baidu.com/image/pic/item/1b4c510fd9f9d72aebede7a1d62a2834359bbb85.jpg", "http://h.hiphotos.baidu.com/image/pic/item/91ef76c6a7efce1be2f4f15cad51f3deb58f654c.jpg", "http://h.hiphotos.baidu.com/image/w=230/sign=3e9ec55457fbb2fb342b5f117f4b2043/e850352ac65c1038343303cbb0119313b07e896e.jpg", "http://e.hiphotos.baidu.com/image/pic/item/d53f8794a4c27d1e3625e52d18d5ad6edcc438dc.jpg" }; private TuTu tu; private Context mContext; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = this; initView(); initAD(); } /** * 初始化轮播图 */ private void initAD() { listADbeans = new ArrayList<ADBean>(); for(int i =0;i<2;i++){ ADBean bean = new ADBean(); bean.setAdName(des[i]); bean.setId(i+""); bean.setImgUrl(urls[i]); //bean.setImgPath(ids[i]); listADbeans.add(bean); } tu = new TuTu(ad_viewPage, tv_msg, ll_dian, mContext, listADbeans); tu.startViewPager(4000);//动态设置滑动间隔,并且开启轮播图 } /** * 初始化布局 */ private void initView() { ad_viewPage = (ViewPager)findViewById(R.id.ad_viewPage); tv_msg = (TextView)findViewById(R.id.tv_msg); ll_dian = (LinearLayout)findViewById(R.id.ll_dian); } /** * 销毁轮播图 */ @Override protected void onDestroy() {  }

}

设置适配器:

public class MyAdapter extends PagerAdapter { List<ADBean> listADbeans=null; OnItemClickListener onItemClickListener; public MyAdapter(List<ADBean> listADbeans) { this.listADbeans = listADbeans; } public int getCount() { //把这个条数数值很大很大 if(listADbeans != null && listADbeans.size()==1){ return 1; }else{ return Integer.MAX_VALUE; } } /**相当于getView:实例化每个页面的View和添加View * container:ViewPage 容器 * position 位置 */ public Object instantiateItem(ViewGroup container, final int position) { //根据位置取出某一个View ImageView view = null; if(listADbeans.size()==1){ view = listADbeans.get(0).getmImageView(); if(listADbeans.get(0).getImgPath() != -1){ view.setBackgroundResource(listADbeans.get(0).getImgPath()); } }else{ view = listADbeans.get(position%listADbeans.size()).getmImageView(); if(listADbeans.get(position%listADbeans.size()).getImgPath() != -1){ view.setBackgroundResource(listADbeans.get(position%listADbeans.size()).getImgPath()); } ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null ) { //parent.removeView(view); container.removeView(view); } view.setScaleType(ScaleType.FIT_XY); //添加到容器 container.addView(view); /** * 添加点击事件 */ view.setOnClickListener(new OnClickListener() { public void onClick(View v) { onItemClickListener.OnItemClick(v, position%listADbeans.size()); } }); return view;//返回实例化的View } /** * 判断view和instantiateItem返回的对象是否一样 * Object : 时instantiateItem返回的对象 */ public boolean isViewFromObject(View view, Object object) { if(view == object){ return true; }else{ return false; } } /**| * 实例化两张图片,最多只能装三张图片 */ public void destroyItem(ViewGroup container, int position, Object object) { //释放资源, //container.removeView((View) object); } public synchronized void notifyImages(List<ADBean> listADbeans){ this.listADbeans = listADbeans; notifyDataSetChanged(); } public interface OnItemClickListener{ void OnItemClick(View view,int position); } public void setOnItemClickListener(OnItemClickListener onItemClickListener){ this.onItemClickListener = onItemClickListener; }

}

线程管理:

/** *      线程管理器 **/public class ThreadPoolManager { private ExecutorService service; private ThreadPoolManager(){ int num = Runtime.getRuntime().availableProcessors(); service = Executors.newFixedThreadPool(num); } private static final ThreadPoolManager manager= new ThreadPoolManager(); public static ThreadPoolManager getInstance(){ return manager; } public void addTask(Runnable runnable){ service.execute(runnable); }}

转载请注明原文地址: https://www.6miu.com/read-2250202.html

最新回复(0)