要实现一个自定义的View 首先要先写一个类
public class CustomBanner extends FrameLayout {
private ViewPager viewPager;
private LinearLayout linearLayout;
private List<String> list;
private int time = 2;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0){
//viewPager显示下一页
viewPager.setCurrentItem(viewPager.getCurrentItem() +1);
//再次发送延时消息
handler.sendEmptyMessageDelayed(0,time*1000);
}
}
};
private ArrayList<ImageView> images;
private OnBannerClickListner bannerClickListner;
public CustomBanner(@NonNull Context context) {
super(context);
init();
}
public CustomBanner(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomBanner(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/**
* 对外提供设置时间
*/
public void setTimeSeconds(int time){
this.time = time;
}
/**
* 初始化的方法,,,加载布局
*/
private void init() {
View view = View.inflate(getContext(), R.layout.custom_banner_layout, this);
//找到控件
viewPager = view.findViewById(R.id.view_pager);
linearLayout = view.findViewById(R.id.linear_layout);
}
/**
* 对外提供设置数据的方法
*/
public void setImageUrl(List<String> list){
this.list = list;
if (list == null){
return;
}
//设置适配器
MyAdapter myAdapter = new MyAdapter(getContext(), list);
//设置适配器
viewPager.setAdapter(myAdapter);
initDoc(list);
//2.手动的可以无限滑动
viewPager.setCurrentItem(list.size()*100000);//设置当前展示中间某个足够大的位置
handler.sendEmptyMessageDelayed(0,time*1000);//发送一个延时的空消息
//viewPage设置监听事件
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
/**
* 当选中某个页面的时候,把当前的小圆点背景变成绿色
* @param position
*/
@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) {
}
});
}
/**
* 动态添加小圆点
* @param list
*/
private void initDoc(List<String> list) {
//1.需要一个集合记录一下小圆点的imageView控件
images = new ArrayList<ImageView>();
//2...linearLayout上面的视图清空一下再去添加
linearLayout.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);
//添加到线性布局上
//这是布局参数,,刚开始小圆点之间没有距离,所以使用java代码指定宽度高度,并且指定小圆点之间的距离
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(5,0,5,0);
linearLayout.addView(imageView,params);
}
}
private class MyAdapter extends PagerAdapter {
Context context;
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;
}
/**
* viewPager具有预加载,默认的前后加载一页,,,默认的容器里面最多三页
* @param container
* @param position
* @return
*/
@Override
public Object instantiateItem(ViewGroup container, final int position) {
//1.把这个当前展示的视图添加到容器中...container
ImageView imageView = new ImageView(context);
//..........使图片平铺整个imageView控件
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//使图片加载到imageview控件上
Glide.with(context).load(list.get(position%list.size())).into(imageView);
//给imageView设置触摸的监听事件
imageView.setOnTouchListener(new View.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) {
bannerClickListner.onBannerClick(position%list.size());
}
});
container.addView(imageView);//添加到容器
//2.把当前展示的视图返回
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//销毁视图
container.removeView((View) object);
}
}
public void setOnBannerClickListner(OnBannerClickListner bannerClickListner){
this.bannerClickListner = bannerClickListner;
}
/**
* 点击的接口
*/
public interface OnBannerClickListner {
public void onBannerClick(int position);
}
}
上面是实现自定义View重要的一不已经写完了 下面就要写MainActivity了
public class MainActivity extends AppCompatActivity {
private int time = 100;
private CustomBanner customBanner;
private List<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customBanner = (CustomBanner) findViewById(R.id.custom_bannner);
customBanner.setTimeSeconds(3);
getDataFromNet();
}
private void getDataFromNet() {
//http://120.27.23.105/ad/getAd
//1.创建一个okhttp客户端对象
OkHttpClient httpClient=new OkHttpClient();
//2.通过请求的构建器来创建一个请求对象,并指定请求的url地址
Request request = new Request.Builder()
.url("http://120.27.23.105/ad/getAd")
.build();
okhttp3.Call call = httpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
if (response.isSuccessful()){
final String string = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("---+++",string);
BannerBean bannerBean = new Gson().fromJson(string, BannerBean.class);
final List<BannerBean.DataBean> data = bannerBean.getData();
list = new ArrayList<>();
for (int i = 0;i<data.size();i++){
list.add(data.get(i).getIcon());
}
customBanner.setImageUrl(list);
//设置点击事件
customBanner.setOnBannerClickListner(new CustomBanner.OnBannerClickListner() {
@Override
public void onBannerClick(int position) {
//Toast.makeText(MainActivity.this,"点击了",Toast.LENGTH_SHORT).show();
//判断
BannerBean.DataBean dataBean = data.get(position);
if (dataBean.getType() == 0){//跳转到详情
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("url",dataBean.getUrl());
startActivity(intent);
}else if (dataBean.getType() == 1){
Toast.makeText(MainActivity.this,"我要跳转到商品详情页",Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
});
}
}
那么还要有轮播图上的小圆点 ,一个是显示当前图片的小圆点 另一个就是 默认状态下的小圆点的颜色了
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#00ff00"/>
<corners android:radius="10dp"/>
<size android:height="10dp" android:width="10dp"/>
</shape>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ff0000"/>
<corners android:radius="10dp"/>
<size android:height="10dp" android:width="10dp"/>
</shape>
这一自定义的那个类需要的布局
<?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/view_pager"
android:layout_width="match_parent"
android:layout_height="200dp">
</android.support.v4.view.ViewPager>
<LinearLayout
android:id="@+id/linear_layout"
android:orientation="horizontal"
android:layout_centerHorizontal="true"
android:layout_alignBottom="@+id/view_pager"
android:layout_marginBottom="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>
</RelativeLayout>
activity的布局
<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"
android:orientation="vertical"
tools:context="test.bwie.com.zidingyilunbo.MainActivity">
<test.bwie.com.zidingyilunbo.view.CustomBanner
android:id="@+id/custom_bannner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>