您的位置:首页 > 移动开发 > Android开发

android轮播图,viewpager加载广告图片

2015-06-09 14:20 591 查看
最近做了一个在首页展示广告轮播图,这几乎是每个应用都会用到的一个功能

在这里和大家分享一下,代码都拷上来了,希望对大家有用

首先在MAinActivity里

package com.example.bbb;

import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.atomic.AtomicInteger;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.content.Context;

import android.support.v4.view.ViewPager;

import android.util.DisplayMetrics;

import android.view.Menu;

import android.view.View;

import android.widget.FrameLayout;

import android.widget.ImageView;

import android.widget.LinearLayout;

public class MainActivity extends Activity {

    public Context mContext;

    private FrameLayout frameLayout;

    private ViewPager vp_ad;

    private double advertWidth = 0;

    private double advertHeight = 0;

    private ImageView[] mImageViews;

    List<CarouselList> carouselLists = new ArrayList<CarouselList>();

    private int currentPosition = 0;

    private boolean iscontinue = true;

    DisplayMetrics dm;

    // 定时任务

    private ScheduledExecutorService scheduledExecutorService;

    private AtomicInteger what = new AtomicInteger(0);

    

    /**

     * Handler

     */

    public Handler loginHandler = new Handler() {

        @Override

        public void handleMessage(Message msg) {

            super.handleMessage(msg);

            switch (msg.what) {

            case 999:

                carouselLists = (List<CarouselList>) msg.obj;//接收服务端传来轮播图信息

                createPoint();

                getTitleView();

                break;

            }

        }

    };

    

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mContext = MainActivity.this;

        // 获取屏幕像素相关信息

        dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        advertWidth = dm.widthPixels;

        advertHeight = (double) dm.widthPixels / 640 * 280;//轮播图的宽高比

        initView();

        InitDate();

    }

    private void initView(){

        frameLayout = (FrameLayout) findViewById(R.id.frameLayout);

        LinearLayout.LayoutParams ff = new LinearLayout.LayoutParams((int)advertWidth, (int)advertHeight);

        frameLayout.setLayoutParams(ff);

        vp_ad = (ViewPager) findViewById(R.id.vp_ad);

    }

    

    /**

     * 调用接口,获取轮播图数据信息,这里我从assets文件中去

     */

    private void InitDate(){

        CarouselList carouselList;

        for(int i=0; i<5; i++){

            carouselList = new CarouselList();

            carouselList.setImg("");//服务端的图片路径

            carouselLists.add(carouselList);

        }

        loginHandler.sendMessage(loginHandler.obtainMessage(999, carouselLists));

    }

    

    private void createPoint() {

        // six index round point

        LinearLayout ll = (LinearLayout) findViewById(R.id.llayout);

        if (ll != null) {

            ll.removeAllViews();

        }

        if (mImageViews != null) {

            mImageViews = null;

        }

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        lp.setMargins(0, 0, 12, 0);

        mImageViews = new ImageView[carouselLists.size()];

        for (int i = 0; i < mImageViews.length; i++) {

            mImageViews[i] = new ImageView(mContext);

            mImageViews[i].setImageResource(R.drawable.guide_round);

            mImageViews[i].setEnabled(true);

            mImageViews[i].setLayoutParams(lp);

            ll.addView(mImageViews[i]);

        }

//        mImageViews[currentPosition].setEnabled(false);

        startPlay();

    }

    

    public void getTitleView() {

        vp_ad.setAdapter(new ViewPagerAdvAdapter(mContext, carouselLists));

        vp_ad.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override

            public void onPageSelected(int pos) {

                // TODO Auto-generated method stub

                currentPosition = pos;

                for (int i = 0; i < mImageViews.length; i++) {

                    if (i == pos) {

                        ((View) mImageViews[pos]).setBackgroundResource(R.drawable.guide_round_current);

                    } else {

                        ((View) mImageViews[i]).setBackgroundResource(R.drawable.guide_round_default);

                    }

                }

            }

            @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

                

                switch (arg0) {

                case 1:

                    iscontinue = false;

                    break;

                case 2:

                    iscontinue = true;

                case 0:

                    if (vp_ad.getCurrentItem() == vp_ad.getAdapter().getCount() - 1

                            && !iscontinue) {

                        vp_ad.setCurrentItem(0);

                    } else if (vp_ad.getCurrentItem() == 0 && !iscontinue) {

                        vp_ad.setCurrentItem(vp_ad.getAdapter().getCount() - 1);

                    }

                default:

                    break;

                }

            }

        });

    }

    

    /**

     * 开始轮播图切换

     */

    private void startPlay() {

        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);

    }

    

    /**

     * 停止轮播图切换

     */

    private void stopPlay() {

        if(scheduledExecutorService != null){

            scheduledExecutorService.shutdown();

        }

    }

    

    /**

     * 执行轮播图切换任务

     *

     * @author caizhiming

     */

    private class SlideShowTask implements Runnable {

        @Override

        public void run() {

            // TODO Auto-generated method stub

            synchronized (vp_ad) {

                currentPosition = (currentPosition + 1) % mImageViews.length;

                handler.obtainMessage().sendToTarget();

            }

        }

    }

    

    private Handler handler = new Handler() {

        @Override

        public void handleMessage(Message msg) {

            // TODO Auto-generated method stub

            super.handleMessage(msg);

            vp_ad.setCurrentItem(currentPosition);

        }

    };

    

    private final Handler viewHandler = new Handler() {

  
d562
     public void handleMessage(Message msg) {

            vp_ad.setCurrentItem(msg.what);

            super.handleMessage(msg);

        }

    };

    

    Runnable runnable = new Runnable() {

        @Override

        public void run() {

            // TODO Auto-generated method stub

            while (true) {

                // if (iscontinue) {

                viewHandler.sendEmptyMessage(what.get());

                whatOption();

                // }

            }

        }

    };

    

    private void setCurPoint(int index) {

        if (index < 0 || index > mImageViews.length || index == currentPosition) {

            return;

        }

        mImageViews[currentPosition].setEnabled(true);

        mImageViews[index].setEnabled(false);

        // set tv title

        currentPosition = index;

    }

    public void whatOption() {

        if (carouselLists != null) {

            what.incrementAndGet();

            if (what.get() > carouselLists.size() - 1) {

                what.getAndAdd(-carouselLists.size());

            }

            try {

                Thread.sleep(3000);

            } catch (Exception e) {

                // TODO: handle exception

            }

        }

    }

    

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

        return true;

    }

}

对应的activity_main.xml文件布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#FFFFFF"

    android:orientation="vertical" >

    <FrameLayout

        android:id="@+id/frameLayout"

        android:layout_width="match_parent"

        android:layout_height="300px" >

        <android.support.v4.view.ViewPager

            android:id="@+id/vp_ad"

            android:layout_width="match_parent"

            android:layout_height="match_parent" />

        <LinearLayout

            android:layout_width="match_parent"

            android:layout_height="30dp"

            android:layout_gravity="bottom"

            android:gravity="center_vertical" >

            <TextView

                android:id="@+id/tv_title"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_marginLeft="2dp"

                android:layout_weight="1" />

            <LinearLayout

                android:id="@+id/llayout"

                android:layout_width="wrap_content"

                android:layout_height="wrap_content"

                android:layout_gravity="right|bottom"

                android:layout_marginBottom="2dp"

                android:layout_marginRight="10dip"

                android:orientation="horizontal" >

            </LinearLayout>

        </LinearLayout>

    </FrameLayout>

</LinearLayout>

加载viewpager的适配:

package com.example.bbb;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.List;

import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.support.v4.view.PagerAdapter;

import android.support.v4.view.ViewPager;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.ImageView;

/**

 * 首页商家广告适配器

 *

 */

public class ViewPagerAdvAdapter extends PagerAdapter implements OnClickListener{

    

    private List<CarouselList> mDatas;

    private List<ImageView> mViews;

    private ImageView mImageView;

    private Context mContext;

    private Bundle mBundle;

    private Intent mIntent;

    

    public ViewPagerAdvAdapter(Context mContext,List<CarouselList> mDatas)

    {

        mIntent = new Intent();

        mBundle = new Bundle();

        this.mContext = mContext;

        mViews = new ArrayList<ImageView>();

        this.mDatas = mDatas;

        int length = mDatas == null ? 0 : mDatas.size();

        

        for(int i=0;i<length;i++)

        {

            ImageView mImageView = new ImageView(mContext);

            mViews.add(mImageView);

        }

        

        length = 0;

    }

    @Override

    public int getCount() {

        

        return mDatas == null ? 0 : mDatas.size();

    }

    @Override

    public boolean isViewFromObject(View arg0, Object arg1) {

        

        return arg0==(arg1);

    }

    

    @Override

    public Object instantiateItem(View container, int position) {

        

        final CarouselList pos = mDatas.get(position);

        mImageView = mViews.get(position);

        

        mImageView.setAdjustViewBounds(true);

        mImageView.setScaleType(ImageView.ScaleType.FIT_XY);

        mImageView.setImageResource(R.drawable.banner);

//        mImageView.setTag(pos);

        mImageView.setOnClickListener(new OnClickListener() {

            

            @Override

            public void onClick(View v) {

                // TODO Auto-generated method stub

                Log.e("111111111111111111", pos.getNeedToken());

                String a = pos.getNeedToken();

//                if(pos.getNeedToken().equals("true")){//点击轮播图跳转广告页面时,是否需要token

//                    if (StaticValues.token == null) {//如果token为空,则去登陆

//                    Intent i = new Intent(mContext, LoginActivity.class);

//                    ((Activity) mContext).startActivityForResult(i, 999);

//                    }else{//不为空,则用webview加载网页

//                        Intent intent = new Intent();

//                        intent.setClass(mContext, WebViewActivity.class);

//                        intent.putExtra("url", pos.getDetail());

//                        intent.putExtra("needToken", "true");

//                        mContext.startActivity(intent);

//                    }

//                }else{

//                    Intent intent = new Intent();

//                    intent.setClass(mContext, WebViewActivity.class);

//                    intent.putExtra("url", pos.getDetail());

//                    mContext.startActivity(intent);

//                }

            }

        });

//        AsyncImageLoader.getInstance(mContext).displayBitmap(mContext,  mImageView, pos.getImg(), true);//异步加载来自服务端的图片

        //这里只固定从assets文件里重复加载一张图片

        Bitmap bm = getBitmapFromAssets("logo.png", mContext);

        mImageView.setImageBitmap(bm);

        ((ViewPager)container).addView(mImageView,0);

        return mImageView;

    }

    

    /**

     * 从assets文件中获取bitmap

     */

    public Bitmap getBitmapFromAssets(String filename, Context mContext) {

        Bitmap bitmap = null;

        InputStream is = null;

        // 从assets中取

            if (null != mContext) {

                try {

                    is = mContext.getResources().getAssets().open(filename);

                    bitmap = BitmapFactory.decodeStream(is);

                    is.close();

                } catch (IOException e) {

                    e.printStackTrace();

                    if (null != bitmap && !bitmap.isRecycled()) {

                        bitmap.recycle();

                        bitmap = null;

                    }

                }

            }

        return bitmap;

    }

    

    @Override

    public void destroyItem(View container, int position, Object object) {

        

        mImageView = mViews.get(position);

        ((ViewPager)container).removeView(mImageView);

    }

    @Override

    public void onClick(View v) {

        // TODO Auto-generated method stub

        

    }

}

保存服务端传来的轮播图数据信息类:

package com.example.bbb;

import java.io.Serializable;

/**

 * 保存服务端传来的轮播图数据信息

 * @author wang

 *

 */

public class CarouselList implements Serializable {

    /**

     *

     */

    private static final long serialVersionUID = -2019212597207279145L;

    private String id;

    private String type;

    private String detail;//点击后要跳转的链接

    private String displayindex;

    private String isshow;

    private String citycode;

    private String img;

    private String clientAct;//客户端动作:webview或者原生页面

    private String needToken;//点击轮播图跳转广告页面时,是否需要token

    public String getNeedToken() {

        return needToken;

    }

    public void setNeedToken(String needToken) {

        this.needToken = needToken;

    }

    public String getId() {

        return id;

    }

    public void setId(String id) {

        this.id = id;

    }

    public String getType() {

        return type;

    }

    public void setType(String type) {

        this.type = type;

    }

    public String getDetail() {

        return detail;

    }

    public void setDetail(String detail) {

        this.detail = detail;

    }

    public String getDisplayindex() {

        return displayindex;

    }

    public void setDisplayindex(String displayindex) {

        this.displayindex = displayindex;

    }

    public String getIsshow() {

        return isshow;

    }

    public void setIsshow(String isshow) {

        this.isshow = isshow;

    }

    public String getCitycode() {

        return citycode;

    }

    public void setCitycode(String citycode) {

        this.citycode = citycode;

    }

    public String getImg() {

        return img;

    }

    public void setImg(String img) {

        this.img = img;

    }

    public String getClientAct() {

        return clientAct;

    }

    public void setClientAct(String clientAct) {

        this.clientAct = clientAct;

    }

}

在assets文件直接放一个图片文件logo.png,在drawable里直接放banner.png,guide_round_current.png,guide_round_default.png,guide_round.xml

guide_round.xml这个xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/guide_round_default" android:state_enabled="true"/>

    <item android:drawable="@drawable/guide_round_current" android:state_enabled="false"/>

</selector>

之后直接运行就OK了,希望可以帮到您
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息