android自定义组合控件图片轮播+小圆点+点击跳转广告页面

1.写一个布局,用于自定义组合控件
<?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="200dp">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="200dp">
    </android.support.v4.view.ViewPager>
    <LinearLayout
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:gravity="center"
        android:id="@+id/ll_buttom"
        android:background="#999999"
        android:layout_width="match_parent"
        android:layout_height="40dp">
    </LinearLayout>
</RelativeLayout>
2.写一个类继承RelativeLayout,也就是自定义组合控件的类
package com.bawei.com.zhanglu201801021511j.Views;

import android.content.Context;
import android.content.Intent;
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.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;



import com.bawei.com.zhanglu201801021511j.R;
import com.bumptech.glide.Glide;

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

/**
 * Created by lenovo on 2018/1/2.
 */

public class MyViewGrop extends RelativeLayout {

    private List<bean.DataBean> list;
    private MyHandler2 myHandler2;

    private ViewPager viewById;
    private LinearLayout ll_buttom;
    private Context Mcontext;
    private Setonhuizhi setonhuizhi;

    public MyViewGrop(Context context) {
        this(context, null);
    }

    public MyViewGrop(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyViewGrop(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //将布局绘制到控件
        LayoutInflater from = LayoutInflater.from(context);
        //加载布局myviewgrop
        View view = from.inflate(R.layout.myviewgrop, this, true);
        //获取id
        viewById = view.findViewById(R.id.viewpager);
        ll_buttom = view.findViewById(R.id.ll_buttom);
        //赋值上下文
        Mcontext = context;

    }


    public void setMyAdapter(Context context, List<bean.DataBean> list) {
        //实力化适配器
        MyAdapter myAdapter = new MyAdapter(context, list);
        //获取适配器
        viewById.setAdapter(myAdapter);
             //写一个集合用于放指示器,也就是小圆点
        final ArrayList<ImageView> points = new ArrayList<>();
        //将指示器添加进去
        for (int i = 0; i < list.size(); i++) {
            //
            ImageView point = new ImageView(context);
            //给图片添加选中和未选中的状态
            point.setBackgroundResource(R.drawable.selected);
            //添加到集合
            points.add(point);
            //放入下面的额线性布局
            ll_buttom.addView(point);
        }
        //默认第一个店选中
        points.get(0).setSelected(true);
        //绑定viewpager的滑动时间
        viewById.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                position = position % points.size();
                for (int i = 0; i < points.size(); i++) {
                    if (i == position) {
                        //如果滑动的图片下标等于圆点下标就是圆点选中
                        points.get(position).setSelected(true);
                    } else {
                        //不等于就不选中
                        points.get(i).setSelected(false);
                    }
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        //2.手动的可以无限滑动  可以左滑
        viewById.setCurrentItem(points.size()*100000);//设置当前展示中间某个足够大的位置
//        viewById.setCurrentItem(Integer.MAX_VALUE/2);
        //设置自动轮播
        myHandler2 = new MyHandler2();
        autoPlay();
        //
    }

    private void autoPlay() {
        myHandler2.sendEmptyMessageDelayed(0, 1000);
    }
    //适配器
    class MyAdapter extends PagerAdapter {
        private Context context;//上下文
        private List<bean.DataBean> list;//集合

        public MyAdapter(Context context, List<bean.DataBean> 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, int position) {
            //因为是无线轮播,所以要魔除集合长度再能获取正常下标
            position = position % list.size();
            //写一个ImageView控件
            ImageView imageView = new ImageView(context);
            //使用Glide加载图片
            Glide.with(context).load(list.get(position).getIcon()).into(imageView);
            //加入容器
            container.addView(imageView);
            imageView.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    switch (event.getAction()){
                        case MotionEvent.ACTION_DOWN://按下的时候应该取消发送消息的操作
                            myHandler2.removeCallbacksAndMessages(null);
                            break;
                        case MotionEvent.ACTION_MOVE://移动的动作
                            myHandler2.removeCallbacksAndMessages(null);
                            break;
                        case MotionEvent.ACTION_CANCEL://取消
                            myHandler2.sendEmptyMessageDelayed(0,2000);
                            break;
                        case MotionEvent.ACTION_UP://抬起的时候
                            myHandler2.sendEmptyMessageDelayed(0,2000);
                            break;
                    }
                    return false;
                }
            });
            //下标
            final int finalPosition = position;
            //给imageView设置触摸的监听事件,再点击的时候要暂停发送
            imageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //获取type
                    int type = list.get(finalPosition).getType();
                    //获取路径
                    String icon = list.get(finalPosition).getUrl();
                    //接口传值
                    setonhuizhi.onsethuizhi(type,icon);
                }
            });
            return imageView;
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            //销毁视图
            container.removeView((View) object);
        }
    }
    //自动轮播
    class MyHandler2 extends Handler {
        @Override
        public void handleMessage(Message msg) {
            //显示下一页的消息
            viewById.setCurrentItem(viewById.getCurrentItem() + 1);
             //  //再次发送
            myHandler2.sendEmptyMessageDelayed(0, 1000);
        }
    }
    //接空
    public interface Setonhuizhi {
        void onsethuizhi(int type,String Url);
    }
     //接口的外部类调用
    public void setonda(Setonhuizhi setonhuizhi) {
        this.setonhuizhi = setonhuizhi;
    }
}
3.小圆点的xml布局背景   建立2个shape.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/shape1"></item>
<item android:state_selected="false" android:drawable="@drawable/shape2"></item>
</selector>

//默认
<?xml version="1.0" encoding="utf-8"?>
<shape
    android:shape="oval"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:width="10dp" android:height="10dp"></size>
    <solid android:color="@android:color/holo_red_dark"></solid>
</shape>

//为true是默认
<?xml version="1.0" encoding="utf-8"?>
<shape
    android:shape="oval"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <size android:width="10dp" android:height="10dp"></size>
    <solid android:color="@android:color/holo_green_dark"></solid>
</shape>
4.mainACtivity的布局和应用
  //布局
  <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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.bawei.com.zhanglu201801021511j.MainActivity">

    <com.bawei.com.zhanglu201801021511j.Views.MyViewGrop
       android:id="@+id/banner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</android.support.constraint.ConstraintLayout>

//应用
package com.bawei.com.zhanglu201801021511j;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.bawei.com.zhanglu201801021511j.Views.MyViewGrop;
import com.bawei.com.zhanglu201801021511j.Views.bean;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private MyViewGrop banner;
    String url = "https://www.zhaoapi.cn/ad/getAd";
    private MyHandler myHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取自定义的控件id
        banner = (MyViewGrop) findViewById(R.id.banner);
        //请求网络数据
        jiexi(url);
        //handler机制
        myHandler = new MyHandler();
        //调用接口传值的方法
        banner.setonda(new MyViewGrop.Setonhuizhi() {
            @Override
            public void onsethuizhi(int type, String Url) {
                //type==1
                if (type == 1) {
                    //意图
                    Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                    //跳转传值
                    intent.putExtra("url", Url);
                    //跳转
                    startActivity(intent);
                } else {
                    //不为1吐司
                    Toast.makeText(MainActivity.this, type + "", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    //数据解析
    public void jiexi(final String url) {
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL u = new URL(url);
                    HttpURLConnection urlConnection = (HttpURLConnection) u.openConnection();
                    urlConnection.setConnectTimeout(8000);
                    if (urlConnection.getResponseCode() == 200) {
                        InputStream inputStream = urlConnection.getInputStream();
                        String s = in2String(inputStream);
                        Gson g = new Gson();
                        bean bean = g.fromJson(s, bean.class);
                        List<com.bawei.com.zhanglu201801021511j.Views.bean.DataBean> data = bean.getData();
                        Log.d("TAG", "gson----" + bean);
                        Message message = new Message();
                        message.obj = data;
                        myHandler.sendMessage(message);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    //将输入流转成字符串
    public String in2String(InputStream is) throws IOException {
        StringBuffer buffer = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String len = "";
        while ((len = br.readLine()) != null) {
            buffer.append(len);
        }
        return buffer.toString();
    }
    //创建Handler对象
    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            List<bean.DataBean> data1 = (List<bean.DataBean>) msg.obj;
            //在这里设置适配器
            banner.setMyAdapter(MainActivity.this, data1);
        }
    }
}
//点击图片跳转到详情页面的activity
//布局
<android.support.constraint.ConstraintLayout 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.zengxianglin1511j20180102.Main2Activity"  
    >  
    //展示网页  
    <WebView  
        android:id="@+id/mWebView"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"></WebView>  

</android.support.constraint.ConstraintLayout> 

//应用
public class Main2Activity extends AppCompatActivity {  
    WebView mWebView;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main2);  
        Intent intent = getIntent();  
        String url = intent.getStringExtra("url");  
        Toast.makeText(Main2Activity.this,url+"aaaa",Toast.LENGTH_LONG).show();  

        mWebView = (WebView) findViewById(R.id.mWebView);  
        mWebView.loadUrl(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();  
    }  

    private void initListener() {  
        /**打开页面时, 自适应屏幕*/  
        WebSettings webSettings =   mWebView .getSettings();  
        webSettings.setUseWideViewPort(true);//设置此属性,可任意比例缩放  
        webSettings.setLoadWithOverviewMode(true);  

        /**便页面支持缩放*/  
        webSettings.setJavaScriptEnabled(true);  
        webSettings.setBuiltInZoomControls(true);  
        webSettings.setSupportZoom(true);  
    }  
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值