Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android圖片輪播+點擊跳轉廣告頁面

android圖片輪播+點擊跳轉廣告頁面

編輯:關於Android編程

一些新手總是很頭疼怎麼獲取網絡圖片的url之後讓它像一些廣告那樣輪播起來,點擊圖片之後跳轉到指定網頁。效果如下

在布局引用自定義控件


  


      
      

MainActivity.java

public class MainActivity extends Activity {

    private String[] imageUrls = new String[]{  
            "http://d.hiphotos.baidu.com/image/pic/item/9f2f070828381f30b2bd028fac014c086e06f074.jpg",  
            "http://h.hiphotos.baidu.com/image/pic/item/2934349b033b5bb55e73afd833d3d539b600bc74.jpg",  
            "http://b.hiphotos.baidu.com/image/pic/item/ac345982b2b7d0a2bdfa8bbbceef76094b369ae1.jpg",  
            "http://g.hiphotos.baidu.com/image/pic/item/2e2eb9389b504fc213023f23e0dde71190ef6db3.jpg" } ;
    private String[] imageUris = new String[]{
            "http://www.baidu.com",
            "http://www.sina.com.cn",
            "http://www.taobao.com",
             "http://www.tudou.com" };

    private List> imageList = new ArrayList>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        for (int i = 0; i < 4; i++) {
            Map image_uri = new HashMap();
            image_uri.put("imageUrls", imageUrls[i]);
            image_uri.put("imageUris", imageUris[i]);
            imageList.add(image_uri);
        }

        SlideShowView view = (SlideShowView) findViewById(R.id.slideshowView); 
        view.setImageUrls(imageList);
    }

}

自定義輪播的詳細實現

public class SlideShowView extends FrameLayout implements OnClickListener{  

    // 使用universal-image-loader插件讀取網絡圖片,需要工程導入universal-image-loader-1.8.6-with-sources.jar  
    private ImageLoader imageLoader = ImageLoader.getInstance();  

    //輪播圖圖片數量  
    private final static int IMAGE_COUNT = 5;  
    //自動輪播的時間間隔  
    private final static int TIME_INTERVAL = 5;  
    //自動輪播啟用開關  
    private final static boolean isAutoPlay = true;   

    //自定義輪播圖的資源  
    private List> imageUrls;  
    //放輪播圖片的ImageView 的list  
    private List imageViewsList;  
    //放圓點的View的list  
    private List dotViewsList;  

    private ViewPager viewPager;  
    //當前輪播頁  
    private int currentItem  = 0;  
    //定時任務  
    private ScheduledExecutorService scheduledExecutorService;  

    private Context context;  

    //Handler  
    private Handler handler = new Handler(){  

        @Override  
        public void handleMessage(Message msg) {  
            // TODO Auto-generated method stub  
            super.handleMessage(msg);  
            viewPager.setCurrentItem(currentItem);  
        }  

    };  

    public SlideShowView(Context context) {  
        this(context,null);  
        // TODO Auto-generated constructor stub  
    }  
    public SlideShowView(Context context, AttributeSet attrs) {  
        this(context, attrs, 0);  
        // TODO Auto-generated constructor stub  
    }  
    public SlideShowView(Context context, AttributeSet attrs, int defStyle) {  
        super(context, attrs, defStyle);  
        this.context = context;  

        initImageLoader(context);  

        if(isAutoPlay){  
            startPlay();  
        }  

    }  
    /** 
     * 開始輪播圖切換 
     */  
    private void startPlay(){  
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();  
        scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4, TimeUnit.SECONDS);  
    }  
    /** 
     * 停止輪播圖切換 
     */  
    private void stopPlay(){  
        scheduledExecutorService.shutdown();  
    }  
    /** 
     * 初始化相關Data 
     */  
    private void initData(){  
        imageViewsList = new ArrayList();  
        dotViewsList = new ArrayList();  
        initUI(context);  
    }  

    public void setImageUrls(List> imageList){
        this.imageUrls = imageList;
         initData();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = null;
        Bundle bundle = null;
        switch (v.getId()) {
        case 0:
            intent = new Intent(context,WebViewActivity.class);
            bundle = new Bundle();
            bundle.putString("url", imageUrls.get(0).get("imageUris"));
            intent.putExtras(bundle);
            context.startActivity(intent);
            break;
        case 1:
            intent = new Intent(context,WebViewActivity.class);
            bundle = new Bundle();
            bundle.putString("url", imageUrls.get(1).get("imageUris"));
            intent.putExtras(bundle);
            context.startActivity(intent);
            break;
        case 2:
            intent = new Intent(context,WebViewActivity.class);
            bundle = new Bundle();
            bundle.putString("url", imageUrls.get(2).get("imageUris"));
            intent.putExtras(bundle);
            context.startActivity(intent);
            break;
        case 3:
            intent = new Intent(context,WebViewActivity.class);
            bundle = new Bundle();
            bundle.putString("url", imageUrls.get(3).get("imageUris"));
            intent.putExtras(bundle);
            context.startActivity(intent);
            break;
        }
    }

    /** 
     * 初始化Views等UI 
     */  
    private void initUI(Context context){  
        if(imageUrls == null || imageUrls.size() == 0)  
            return;  

        LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this, true);  

        LinearLayout dotLayout = (LinearLayout)findViewById(R.id.dotLayout);  
        dotLayout.removeAllViews();  

        // 熱點個數與圖片特殊相等  
        for (int i = 0; i < imageUrls.size(); i++) {  
            ImageView view =  new ImageView(context);  
            view.setId(i);
            view.setTag(imageUrls.get(i).get("imageUrls"));  
            if(i==0)//給一個默認圖  
                view.setBackgroundResource(R.drawable.detail_p1);  
            view.setScaleType(ScaleType.FIT_XY);  
            view.setOnClickListener(this);
            imageViewsList.add(view);  

            ImageView dotView =  new ImageView(context);  
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);  
            params.leftMargin = 4;  
            params.rightMargin = 4;  
            dotLayout.addView(dotView, params);  
            dotViewsList.add(dotView);  
        }  

        viewPager = (ViewPager) findViewById(R.id.viewPager);  
        viewPager.setFocusable(true);  

        viewPager.setAdapter(new MyPagerAdapter());  
        viewPager.setOnPageChangeListener(new MyPageChangeListener());  
    }  

    /** 
     * 填充ViewPager的頁面適配器 
     *  
     */  
    private class MyPagerAdapter  extends PagerAdapter{  

        @Override  
        public void destroyItem(View container, int position, Object object) {  
            // TODO Auto-generated method stub  
            //((ViewPag.er)container).removeView((View)object);  
            ((ViewPager)container).removeView(imageViewsList.get(position));  
        }  

        @Override  
        public Object instantiateItem(View container, int position) {  
            ImageView imageView = imageViewsList.get(position);  

            imageLoader.displayImage(imageView.getTag() + "", imageView);  

            ((ViewPager)container).addView(imageViewsList.get(position));  
            return imageViewsList.get(position);  
        }  

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

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

        }  

        @Override  
        public Parcelable saveState() {  
            // TODO Auto-generated method stub  
            return null;  
        }  

        @Override  
        public void startUpdate(View arg0) {  
            // TODO Auto-generated method stub  

        }  

        @Override  
        public void finishUpdate(View arg0) {  
            // TODO Auto-generated method stub  

        }  

    }  
    /** 
     * ViewPager的監聽器 
     * 當ViewPager中頁面的狀態發生改變時調用 
     *  
     */  
    private class MyPageChangeListener implements OnPageChangeListener{  

        boolean isAutoPlay = false;  

        @Override  
        public void onPageScrollStateChanged(int arg0) {  
            // TODO Auto-generated method stub  
            switch (arg0) {  
            case 1:// 手勢滑動,空閒中  
                isAutoPlay = false;  
                break;  
            case 2:// 界面切換中  
                isAutoPlay = true;  
                break;  
            case 0:// 滑動結束,即切換完畢或者加載完畢  
                // 當前為最後一張,此時從右向左滑,則切換到第一張  
                if (viewPager.getCurrentItem() == viewPager.getAdapter().getCount() - 1 && !isAutoPlay) {  
                    viewPager.setCurrentItem(0);  
                }  
                // 當前為第一張,此時從左向右滑,則切換到最後一張  
                else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {  
                    viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 1);  
                }  
                break;  
        }  
        }  

        @Override  
        public void onPageScrolled(int arg0, float arg1, int arg2) {  
            // TODO Auto-generated method stub  

        }  

        @Override  
        public void onPageSelected(int pos) {  
            // TODO Auto-generated method stub  

            currentItem = pos;  
            for(int i=0;i < dotViewsList.size();i++){  
                if(i == pos){  
                    ((View)dotViewsList.get(pos)).setBackgroundResource(R.drawable.compose_guide_check_box_number);  
                }else {  
                    ((View)dotViewsList.get(i)).setBackgroundResource(R.drawable.compose_guide_check_box_default);  
                }  
            }  
        }  

    }  

    /** 
     *執行輪播圖切換任務 
     */  
    private class SlideShowTask implements Runnable{  

        @Override  
        public void run() {  
            // TODO Auto-generated method stub  
            synchronized (viewPager) {  
                currentItem = (currentItem+1)%imageViewsList.size();  
                handler.obtainMessage().sendToTarget();  
            }  
        }  

    }  

    /** 
     * 銷毀ImageView資源,回收內存 
     */  
    private void destoryBitmaps() {  

        for (int i = 0; i < IMAGE_COUNT; i++) {  
            ImageView imageView = imageViewsList.get(i);  
            Drawable drawable = imageView.getDrawable();  
            if (drawable != null) {  
                //解除drawable對view的引用  
                drawable.setCallback(null);  
            }  
        }  
    }  


    public static void initImageLoader(Context context) {  
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                                            .threadPriority(Thread.NORM_PRIORITY - 2)
                                            .denyCacheImageMultipleSizesInMemory()
                                            .discCacheFileNameGenerator(new Md5FileNameGenerator())
                                            .tasksProcessingOrder(QueueProcessingType.LIFO)
                                            .writeDebugLogs() 
                                            .build();  
        ImageLoader.getInstance().init(config);  
    }

}  

帶指示器的布局


  

      

      

          

          

      
 

點擊廣告跳轉的web

public class WebViewActivity extends Activity{

    private WebView mWebView;
    private TextView mTitle;
    private ImageButton mBackBtn;
    private Bundle mBundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        setContentView(R.layout.activity_web);
        super.onCreate(savedInstanceState);
        mBundle = getIntent().getExtras();
        initView();
    }

    public void initView() {
        // TODO Auto-generated method stub
        mWebView = (WebView) findViewById(R.id.web_webview);
        mWebView.loadUrl(mBundle.getString("url"));
        mWebView.requestFocusFromTouch();
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        /**覆蓋調用系統或自帶浏覽器行為打開網頁*/
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                view.loadUrl(url);
                return true;
            }
        });
        /**判斷加載過程*/
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO Auto-generated method stub
                if (newProgress == 100) {
                    // 網頁加載完成

                } else {
                    // 加載中

                }
            }
        });
        initListener();
    }

    public void initListener() {
        // TODO Auto-generated method stub
        /**加載javascript*/
//      WebSettings mWebSetting = mWebView.getSettings();
//      mWebSetting.setJavaScriptEnabled(true);
//      mWebView.addJavascriptInterface(new Object() {       
//            public void clickOnAndroid() {       
//                new Handler().post(new Runnable() {       
//                    public void run() {       
//                      mWebView.loadUrl("javascript:wave()");       
//                    }       
//                });       
//            }       
//        }, "demo");

         /**打開頁面時, 自適應屏幕*/
         WebSettings webSettings =   mWebView .getSettings();       
         webSettings.setUseWideViewPort(true);//設置此屬性,可任意比例縮放
         webSettings.setLoadWithOverviewMode(true);

         /**便頁面支持縮放*/
         webSettings.setJavaScriptEnabled(true);  
         webSettings.setBuiltInZoomControls(true);
         webSettings.setSupportZoom(true);

    }

}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved