自定义banner

main布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="com.bwie.z.autobanner.MainActivity">

   <com.bwie.z.autobanner.AutoBanner
       android:id="@+id/autobanner"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

   </com.bwie.z.autobanner.AutoBanner>

</LinearLayout>

web布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bwie.z.autobanner.WebActivity">

    <WebView
        android:id="@+id/web_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></WebView>
</LinearLayout>

banner布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v4.view.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="200dp">

    </android.support.v4.view.ViewPager>
    <LinearLayout
        android:id="@+id/circle"
        android:orientation="horizontal"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/vp"
        android:layout_marginBottom="10dp">

    </LinearLayout>
</RelativeLayout>

shape布局

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#fff"/>
    <corners android:radius="10dp"/>
    <size android:height="10dp" android:width="10dp"/>
</shape>

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#0f0"/>
    <corners android:radius="10dp"/>
    <size android:height="10dp" android:width="10dp"/>
</shape>

value文件夹下attrs的布局

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <declare-styleable name="AutoBanner">
        <attr name="aspectRatio" format="float" />   <!-- 宽高比 -->
        <attr name="defaultSrc" format="integer|reference" />     <!-- 占位图 -->
        <attr name="updateTime" format="integer" />     <!-- 图片切换时间 -->
        <attr name="indicatorVisible" format="boolean" /> <!-- 是否显示指示器 -->
        <attr name="indicatorHeight" format="dimension" /> <!-- 指示器的高度 -->
        <attr name="indicatorBackground" format="color|reference" />    <!-- 指示器的背景颜色 -->
        <attr name="indicatorPositionSize" format="dimension" /> <!-- 指示点的大小 -->
    </declare-styleable>
</resources>

MainActivity

package com.bwie.z.autobanner;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private List<String> list;
    private AutoBanner autoBanner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        autoBanner = (AutoBanner) findViewById(R.id.autobanner);
        getDataFromNet();
    }

    public void getDataFromNet() {
        //1.创建一个okhttp客户端对象
        OkHttpClient httpClient=new OkHttpClient();
        //2.通过请求的构建器来创建一个请求对象,并指定请求的url地址
        Request request = new Request.Builder()
                .url("http://120.27.23.105/ad/getAd")
                .build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    final String string = response.body().string();
                    runOnUiThread(new Runnable() {



                        @Override
                        public void run() {
                            Bean bean= new Gson().fromJson(string,Bean.class);
                            final List<Bean.DataBean> data = bean.getData();
                            list = new ArrayList<String>();
                            for (int i = 0;i<data.size();i++){
                                list.add(data.get(i).getIcon());
                            }
                            autoBanner.setImage(list);
                            autoBanner.setOnBannerListener(new AutoBanner.OnBannerListener(){

                                @Override
                                public void onBanner(int position) {
                                    Bean.DataBean dataBean = data.get(position);
                                    if (dataBean.getType() == 0){//跳转到详情
                                        Intent intent = new Intent(MainActivity.this,WebActivity.class);
                                        intent.putExtra("url",dataBean.getUrl());
                                        startActivity(intent);

                                    }else if (dataBean.getType() == 1){
                                        Toast.makeText(MainActivity.this,"我要跳转到商品详情页",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
    }
}

AutoBanner

package com.bwie.z.autobanner;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;


public class AutoBanner extends FrameLayout{
    private int time=2;
    private List<String> list;
    private ViewPager vp;
    private LinearLayout circle;
    private OnBannerListener bannerListener;
    private ImageView imageView;
    private ArrayList<ImageView> images;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0){
                vp.setCurrentItem(vp.getCurrentItem()+1);
                handler.sendEmptyMessageDelayed(0,time*1000);
            }
        }
    };


    public AutoBanner(Context context) {
        super(context);
        init();
    }

    public AutoBanner(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public AutoBanner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        View view = View.inflate(getContext(), R.layout.banner, this);
        vp = (ViewPager) findViewById(R.id.vp);
        circle = (LinearLayout) findViewById(R.id.circle);
    }
    public void setTime(int time){
        this.time=time;
    }

    public void setImage(List<String> list){
        this.list=list;
        if (list==null){
            return;
        }
        MyAdapter myAdapter=new MyAdapter(getContext(),list);
        vp.setAdapter(myAdapter);
        initCircle(list);
        vp.setCurrentItem(list.size() * 100000);//设置当前展示中间某个足够大的位置

        handler.sendEmptyMessageDelayed(0, time * 1000);//发送一个延时的空消息

        //viewPage设置监听事件
        vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {

                for (int i = 0; i < images.size(); i++) {
                    if (i == position % images.size()) {

                        images.get(i).setImageResource(R.drawable.shape_01);
                    } else {
                        images.get(i).setImageResource(R.drawable.shape_02);
                    }

                }

            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initCircle(List<String> list) {
        images = new ArrayList<>();
        circle.removeAllViews();
        for (int i=0;i<list.size();i++){
            ImageView imageView = new ImageView(getContext());
            if (i == 0) {
                imageView.setImageResource(R.drawable.shape_01);
            }else {
                imageView.setImageResource(R.drawable.shape_02);
            }
            images.add(imageView);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(5, 0, 5, 0);
            circle.addView(imageView, params);
        }

    }

    public class MyAdapter extends PagerAdapter{

        private Context context;
        private List<String> list;


        public MyAdapter(Context context, List<String> list) {
            this.context = context;
            this.list = list;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view==object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            Glide.with(context).load(list.get(position%list.size())).into(imageView);
            imageView.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    int action = motionEvent.getAction();
                    switch (action){
                        case MotionEvent.ACTION_DOWN:
                            handler.removeCallbacksAndMessages(null);
                            break;
                        case MotionEvent.ACTION_MOVE:
                            handler.removeCallbacksAndMessages(null);
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            handler.sendEmptyMessageDelayed(0,time*1000);
                            break;
                        case MotionEvent.ACTION_UP:
                            handler.sendEmptyMessageDelayed(0,time*1000);
                            break;
                    }
                    return false;
                }
            });
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    bannerListener.onBanner(position%list.size());
                }
            });
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
    public void setOnBannerListener(OnBannerListener bannerListener){
        this.bannerListener=bannerListener;
    }
    public interface OnBannerListener{
        public void onBanner(int position);
    }
}

WebActivity

package com.bwie.z.autobanner;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        WebView webView = (WebView) findViewById(R.id.web_view);
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");

        //加载
        webView.loadUrl(url);

        //设置
        webView.setWebViewClient(new WebViewClient());

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值