如何使用Volley在Android的Slide ViewPager中获取图像

时间:2019-01-07 12:19:45

标签: android android-volley

API文件

METHOD : POST
PARAMETER TO PASS:

INPUT:

OUTPUT:
{
    "status": true,
    "result": {
        "sliderImg": [
            {
                "slidername": "slider 1",
                "imagename": "http://192.168.1.80/slider/slider1.jpg"
            },
            {
                "slidername": "slider 2",
                "imagename": "http://192.168.1.80/slider/slider2.jpg"
            },
        ],
        "categoryImg": [
            {
                "cat_id": "1",
                "cat_name": "Automotive Battery chargers",
                "image_name": "http://192.168.1.80/cat/Automotive.png.png"
            },
            {
                "cat_id": "2",
                "cat_name": "CVCC Chargers",
                "image_name": "http://192.168.1.80/cat/CVCC_Charger.png"
            }
        ]
    },
    "message": "Get Dashboard successfully!"
}

模型类

public class MyPojo
{
    private String message;

    private Result result;

    private String status;

    public String getMessage ()
    {
        return message;
    }

    public void setMessage (String message)
    {
        this.message = message;
    }

    public Result getResult ()
    {
        return result;
    }

    public void setResult (Result result)
    {
        this.result = result;
    }

    public String getStatus ()
    {
        return status;
    }

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

    @Override
    public String toString()
    {
        return "ClassPojo [message = "+message+", result = "+result+", status = "+status+"]";
    }
}



    public class Result
    {
    private SliderImg[] sliderImg;

    private CategoryImg[] categoryImg;

    public SliderImg[] getSliderImg ()
    {
        return sliderImg;
    }

    public void setSliderImg (SliderImg[] sliderImg)
    {
        this.sliderImg = sliderImg;
    }

    public CategoryImg[] getCategoryImg ()
    {
        return categoryImg;
    }

    public void setCategoryImg (CategoryImg[] categoryImg)
    {
        this.categoryImg = categoryImg;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [sliderImg = "+sliderImg+", categoryImg = "+categoryImg+"]";
    }
}




public class CategoryImg
{
    private String cat_id;

    private String image_name;

    private String cat_name;

    public String getCat_id ()
    {
        return cat_id;
    }

    public void setCat_id (String cat_id)
    {
        this.cat_id = cat_id;
    }

    public String getImage_name ()
    {
        return image_name;
    }

    public void setImage_name (String image_name)
    {
        this.image_name = image_name;
    }

    public String getCat_name ()
    {
        return cat_name;
    }

    public void setCat_name (String cat_name)
    {
        this.cat_name = cat_name;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [cat_id = "+cat_id+", image_name = "+image_name+", cat_name = "+cat_name+"]";
    }
}



public class SliderImg
{
    private String slidername;

    private String imagename;

    public String getSlidername ()
    {
        return slidername;
    }

    public void setSlidername (String slidername)
    {
        this.slidername = slidername;
    }

    public String getImagename ()
    {
        return imagename;
    }

    public void setImagename (String imagename)
    {
        this.imagename = imagename;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [slidername = "+slidername+", imagename = "+imagename+"]";
    }
}

适配器类

public class ViewPagerAdapter extends PagerAdapter {

    private Context context;
    private LayoutInflater layoutInflater;
    private List<SliderImg> sliderImg;
    private ImageLoader imageLoader;


    public ViewPagerAdapter(List sliderImg, Context context) {
        this.sliderImg = sliderImg;
        this.context = context;
    }


    @Override
    public int getCount() {
        return sliderImg.size();
    }


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


    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.dashboard_slide_layout, null);

        SliderImg utils = sliderImg.get(position);

        ImageView imageView = (ImageView) view.findViewById(R.id.dash_img_slider_view);

        imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
        imageLoader.get(utils.getImagename(), ImageLoader.getImageListener(imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));


        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (position == 0) {
                    Toast.makeText(context, "Slide 1 Clicked", Toast.LENGTH_SHORT).show();
                } else if (position == 1) {
                    Toast.makeText(context, "Slide 2 Clicked", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Slide 3 Clicked", Toast.LENGTH_SHORT).show();
                }

            }
        });

        ViewPager vp = (ViewPager) container;
        vp.addView(view, 0);
        return view;

    }


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

        ViewPager vp = (ViewPager) container;
        View view = (View) object;
        vp.removeView(view);

    }
}

自定义批量请求类别

public class CustomVolleyRequest {

    private static CustomVolleyRequest customVolleyRequest;
    private static Context context;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;


    private CustomVolleyRequest(Context context){

        this.context = context;
        this.requestQueue = getRequestQueue();


        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {

            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });

    }


    public static synchronized CustomVolleyRequest getInstance(Context context){

        if(customVolleyRequest == null){
            customVolleyRequest = new CustomVolleyRequest(context);
        }
        return customVolleyRequest;
    }


    public RequestQueue getRequestQueue(){
        if(requestQueue == null){
            Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
            Network network = new BasicNetwork(new HurlStack());
            requestQueue = new RequestQueue(cache, network);
            requestQueue.start();
        }
        return requestQueue;
    }


    public  void addToRequestQueue(Request req) {
        getRequestQueue().add(req);
    }


    public ImageLoader getImageLoader(){

        return imageLoader;
    }
}

MainActivity

 ViewPager viewPager;
    LinearLayout sliderDotspanel;
    private int dotscount;
    private ImageView[] dots;

    RequestQueue rq;
    List<SliderImg> sliderImg;
    ViewPagerAdapter viewPagerAdapter;

    String request_url = " http://192.168.1.80/appapi/dashboard";



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


        rq = CustomVolleyRequest.getInstance(this).getRequestQueue();

        sliderImg = new ArrayList<>();

        viewPager = (ViewPager) findViewById(R.id.dash_pager_introduction);

        sliderDotspanel = (LinearLayout) findViewById(R.id.dash_view_pager_count_dots);

        sendRequest();


        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                for(int i = 0; i< dotscount; i++){
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_selected_item_dot));
                }
                dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.selected_item_dot));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        /*
         * Initiatization of views
         * */
        initializingViews();

}

  private void sendRequest() {

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, request_url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                for(int i = 0; i < response.length(); i++){

                    SliderImg sliderUtils = new SliderImg();

                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        sliderUtils.setImagename(jsonObject.getString("imagename"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    sliderImg.add(sliderUtils);

                }

                viewPagerAdapter = new ViewPagerAdapter(sliderImg, MainActivity.this);

                viewPager.setAdapter(viewPagerAdapter);

                dotscount = viewPagerAdapter.getCount();
                dots = new ImageView[dotscount];

                for(int i = 0; i < dotscount; i++){

                    dots[i] = new ImageView(MainActivity.this);
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_selected_item_dot));

                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                    params.setMargins(8, 0, 8, 0);

                    sliderDotspanel.addView(dots[i], params);

                }

                dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.selected_item_dot));

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        CustomVolleyRequest.getInstance(this).addToRequestQueue(jsonArrayRequest);

    }

我正在尝试使用齐射在ViewPager Sliderby中获取图像,但出现了一些问题。上面我已经给出了完整的代码。在MainActivity中,设置viewPager滑块后,通过使用凌空请求调用sendRequest方法。我不知道如何通过Volley在Slider中获取图像。请帮助我。

1 个答案:

答案 0 :(得分:0)

使用毕加索

implementation 'com.squareup.picasso:picasso:2.5.2'

上述库添加build.gradle

Picasso.with(getApplicationContext()).load(utils.getImagename()).placeholder(R.mipmap.ic_launcher).into(imageView );