Android 用Json解析请求图片写的一个ViewPager广告轮播 , 带滑动小圆点 ,完美解决了三张图片引起的滑动问题

时间:2022-01-19 20:43:36

这是一个通过json解析网络请求的广告轮播,还有自己写的一个小圆点,会跟着图片一块动,滑动流畅,不会出现无响应的情况,喜欢的可以进来看看,希望能帮到你们。

这是两个依赖包:

compile 'com.github.bumptech.glide:glide:3.7.0'

compile 'com.squareup.okhttp3:okhttp:3.5.0'

下面是配置清单需要配置的权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 

下面是xml布局:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="240dp">
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="240dp"/>
    <LinearLayout
        android:id="@+id/mLayou"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_alignParentBottom="true"></LinearLayout>
</RelativeLayout>

主界面:

MainActivity

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

public class MainActivity extends Activity implements OkUtils.LoadData {
    private String path="http://litchiapi.jstv.com/api/getTops?limit=5&column=0&val=F467412B44B421716757A6B2D7635B4A";
    private ViewPager mVp;
    private LinearLayout mLayout;
    private ArrayList<ImageView>views = new ArrayList<>();
    private ArrayList<ImageView>dots = new ArrayList<>();
    private int currentIndex = 0;
    private boolean isTouch = false;
    private boolean isAuto = true;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                if(isTouch){
                    return;
                }
                currentIndex++;
                mVp.setCurrentItem(currentIndex);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        OkUtils utils=new OkUtils(this,this);
        utils.getRequest(path);
        thread.start();
    }

    Thread thread = new Thread(new Runnable() {

        public void run() {
            while(isAuto){
                try {
                    thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessage(0);
            }
        }
    });

    private void initView() {
        mVp = (ViewPager) findViewById(R.id.viewpager);
        mLayout = (LinearLayout) findViewById(R.id.mLayou);
        mVp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                currentIndex = mVp.getCurrentItem();
                for(int i=0;i<dots.size();i++){
                    if(position%dots.size()==i){
                        dots.get(i).setImageResource(R.mipmap.dian1);
                    }else{
                        dots.get(i).setImageResource(R.mipmap.dian);
                    }
                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if(state == ViewPager.SCROLL_STATE_IDLE){
                    isTouch = false;
                }else{
                    isTouch = true;
                }

            }
        });
    }
    public void loadData(String json) {
        JsonUtils utils = new JsonUtils();
        JavaBean pzjson = utils.getJson(json);
        if(pzjson!=null && pzjson.getStatus().equals("ok")){
            ArrayList<JavaBean.Paramz.Tops>topses = pzjson.getParamz().getTops();
            for(int i=0;i<topses.size();i++){
                ImageView imageView = new ImageView(this);
                imageView.setLayoutParams(new                 ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,                 ViewGroup.LayoutParams.MATCH_PARENT));
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                Glide.with(this).load("http://litchiapi.jstv.com"+topses.get(i).getPhoto()).into(imageView);
                views.add(imageView);

                ImageView dot = new ImageView(this);
                dot.setLayoutParams(new ViewGroup.LayoutParams(20,20));
                dot.setScaleType(ImageView.ScaleType.FIT_XY);
                dot.setImageResource(R.mipmap.dian);
                mLayout.addView(dot);
                dots.add(dot);
            }
            dots.get(0).setImageResource(R.mipmap.dian1);
        }
        if(views!=null){
            MyPagerAdapter adapter = new MyPagerAdapter();
            mVp.setAdapter(adapter);
        }
    }
    class MyPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if(views.size()>0){
                return Integer.MAX_VALUE;
            }
            return 0;
        }

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

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            position %= views.size();
            ViewGroup group = (ViewGroup) views.get(position).getParent();
            if(group!=null){
                group.removeView(views.get(position));
            }
            container.addView(views.get(position));
            return views.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

        }
    }
}
OkUtils(这个是封装的一个Okhttp的网络请求工具类)   
import android.content.Context;
import android.net.ConnectivityManager;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

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

 public class OkUtils {
    private Context context;
    private OkHttpClient okClient;
    private LoadData loadData;
    public OkUtils(Context context,LoadData loadData){
        this.context = context;
        this.loadData = loadData;
    }
    public OkHttpClient getOkClient(){
        if(okClient==null){
            synchronized (this){
                if(okClient==null){
                    okClient = new OkHttpClient.Builder()
                            .connectTimeout(5, TimeUnit.SECONDS)
                            .readTimeout(5,TimeUnit.SECONDS)
                            .build();
                }
            }
        }
        return okClient;
    }
    public boolean isConnected(){
        boolean flag = false;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(manager.getActiveNetworkInfo()!= null){
            flag = manager.getActiveNetworkInfo().isConnected();
        }
        return flag;
    }

    public void getRequest(String path){
        if(isConnected()){
            OkHttpClient client = getOkClient();
            Request request = new Request.Builder()
                    .url(path)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException                       {
                    final String str = response.body().string();
                    if(str!=null){
                        ((MainActivity)context).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                loadData.loadData(str);
                            }
                        });
                    }
                }
            });
        }
    }
    public interface LoadData {
        void loadData(String json);
    }
}
JsonUtils                                                                
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

 public class JsonUtils {
    public JavaBean getJson(String json){
        JavaBean json1=new JavaBean();
        try {
            JSONObject object = new JSONObject(json);
//            Json.setStatus(object.optString("status"));
            json1.setStatus(object.optString("status"));
            JavaBean.Paramz paramz = json1.new Paramz();
            JSONObject ob1 = object.optJSONObject("paramz");

            ArrayList<JavaBean.Paramz.Tops> topses = new ArrayList<>();
            JSONArray array = ob1.optJSONArray("tops");

            for(int i=0;i<array.length();i++){
                JSONObject ob2 = array.optJSONObject(i);

                int id = ob2.optInt("id");
                int oid = ob2.optInt("oid");
                String category = ob2.optString("category");
                String photo = ob2.optString("photo");
                String subject = ob2.optString("subject");
                JavaBean.Paramz.Tops tops = paramz.new                    Tops(id,oid,category,photo,subject);
                topses.add(tops);
            }
            paramz.setTops(topses);
            json1.setParamz(paramz);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json1;
    }
}
JavaBean
import java.util.ArrayList;

 public class JavaBean {
    private String status;
    private Paramz paramz;

    public String getStatus() {
        return status;
    }

    public  void setStatus(String status) {
        this.status = status;
    }

    public Paramz getParamz() {
        return paramz;
    }

    public void setParamz(Paramz paramz) {
        this.paramz = paramz;
    }

    public class Paramz{
        private ArrayList<Tops> tops;

        public ArrayList<Tops> getTops() {
            return tops;
        }

        public void setTops(ArrayList<Tops> tops) {
            this.tops = tops;
        }

        public class Tops{
            private int id;
            private int oid;
            private String category;
            private String photo;
            private String subject;

            public Tops(int id, int oid, String category, String photo, String subject) {
                this.id = id;
                this.oid = oid;
                this.category = category;
                this.photo = photo;
                this.subject = subject;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public int getOid() {
                return oid;
            }

            public void setOid(int oid) {
                this.oid = oid;
            }

            public String getCategory() {
                return category;
            }

            public void setCategory(String category) {
                this.category = category;
            }

            public String getPhoto() {
                return photo;
            }

            public void setPhoto(String photo) {
                this.photo = photo;
            }

            public String getSubject() {
                return subject;
            }

            public void setSubject(String subject) {
                this.subject = subject;
            }
        }
    }
}