在ViewPager Android中设置来自网址的图片

时间:2015-11-20 04:14:30

标签: android android-fragments android-viewpager

我正在关注this tutorial在我的项目中实施ViewPager。我已成功使用静态图片。现在我想更改它,以便从网址中检索图像并显示在ViewPager中。以下是我的代码。

  

我应该在哪里添加下载图像的方法以及如何设置图像   到我的ViewPager

非常感谢任何帮助。

MainActivity:

public class MainActivity extends AppCompatActivity {

    private ArrayList<Integer> images;
    private BitmapFactory.Options options;
    private ViewPager viewPager;
    private View btnNext, btnPrev;
    private FragmentStatePagerAdapter adapter;
    private LinearLayout thumbnailsContainer;
    private final static int[] resourceIDs = new int[]{R.mipmap.a, R.mipmap.b,
            R.mipmap.c, R.mipmap.d, R.mipmap.e, R.mipmap.f, R.mipmap.g};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        images = new ArrayList<>();

        //find view by id
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        thumbnailsContainer = (LinearLayout) findViewById(R.id.container);
        btnNext = findViewById(R.id.next);
        btnPrev = findViewById(R.id.prev);

        btnPrev.setOnClickListener(onClickListener(0));
        btnNext.setOnClickListener(onClickListener(1));

        setImagesData();

        // init viewpager adapter and attach
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), images);
        viewPager.setAdapter(adapter);

        inflateThumbnails();
    }

    private View.OnClickListener onClickListener(final int i) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (i > 0) {
                    //next page
                    if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
                        viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                    }
                } else {
                    //previous page
                    if (viewPager.getCurrentItem() > 0) {
                        viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
                    }
                }
            }
        };
    }

    private void setImagesData() {
        for (int i = 0; i < resourceIDs.length; i++) {
            images.add(resourceIDs[i]);
        }
    }

    private void inflateThumbnails() {
        for (int i = 0; i < images.size(); i++) {
            View imageLayout = getLayoutInflater().inflate(R.layout.item_image, null);
            ImageView imageView = (ImageView) imageLayout.findViewById(R.id.img_thumb);
            imageView.setOnClickListener(onChagePageClickListener(i));
            options = new BitmapFactory.Options();
            options.inSampleSize = 3;
            options.inDither = false;
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), images.get(i), options );
            imageView.setImageBitmap(bitmap);
            //set to image view
            imageView.setImageBitmap(bitmap);
            //add imageview
            thumbnailsContainer.addView(imageLayout);
        }
    }

    private View.OnClickListener onChagePageClickListener(final int i) {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewPager.setCurrentItem(i);
            }
        };
    }
}

PageFragment类:

   public class PageFragment extends Fragment {

        private int imageResource;
        private Bitmap bitmap;

        public static PageFragment getInstance(int resourceID) {
            PageFragment f = new PageFragment();
            Bundle args = new Bundle();
            args.putInt("image_source", resourceID);
            f.setArguments(args);
            return f;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            imageResource = getArguments().getInt("image_source");
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_page, container, false);
        }

        @Override
        public void onViewCreated(View view, Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            ImageView imageView = (ImageView) view.findViewById(R.id.image);

            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inSampleSize = 4;
            o.inDither = false;
            bitmap = BitmapFactory.decodeResource(getResources(), imageResource, o);
            imageView.setImageBitmap(bitmap);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            bitmap.recycle();
            bitmap = null;
        }
    }

ViewPager Adapter class:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    private List<Integer> images;

    public ViewPagerAdapter(FragmentManager fm, List<Integer> imagesList) {
        super(fm);
        this.images = imagesList;
    }

    @Override
    public Fragment getItem(int position) {
        return PageFragment.getInstance(images.get(position));
    }

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

7 个答案:

答案 0 :(得分:11)

要对图像使用 ViewPager ,您必须制作一个扩展 PagerAdapter 的适配器,如下所示:

public class ImagePagerAdapter extends PagerAdapter {

    Context context;
    LayoutInflater layoutInflater;

    ArrayList<String> arrayList;

    public ImagePagerAdapter(Context context, ArrayList<String> arrayList) {
        this.context = context;
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.arrayList = arrayList;
    }

    @Override
    public int getCount() {
        if(arrayList != null){
            return arrayList.size();
        }
        return 0;
    }

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

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View itemView = layoutInflater.inflate(R.layout.image_viewpager_layout, container, false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.viewPagerItem_image1);

        Picasso.with(context).load(arrayList.get(position))
                            .placeholder(R.drawable.image_uploading)
                            .error(R.drawable.image_not_found).into(imageView);

        container.addView(itemView);

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout) object);
    }

}

适配器的xml布局是:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


        <ImageView
            android:id="@+id/viewPagerItem_image1"
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:scaleType="fitXY"
            android:src="@drawable/ic_launcher"/>


</LinearLayout>

答案 1 :(得分:2)

要从URL下载图片,您必须使用AsyncTask

以下是DownloadImageFromAsyncTask的示例。

new LoadImage().execute("http://www.sumtrix.com/images/sumtrix/Android-Wallpaper-HD.jpg");

将您的网址设置为以上网址。

private class LoadImage extends AsyncTask<String, String, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(MainActivity.this);
            dialog.setMessage("Loading Image...");
            dialog.show();

        }

        @Override
        protected Bitmap doInBackground(String... params) {

            try {
                bitmap = BitmapFactory.decodeStream((InputStream) new URL(params[0]).getContent());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                img.setImageBitmap(result);
                dialog.dismiss();
            } else {
                dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Image Does Not Exist...",
                        Toast.LENGTH_LONG).show();
            }

        }

    }

为此你必须在AndroidManifest.xml文件中添加权限

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

答案 2 :(得分:1)

IMO你应该在这里设置你的图像,你的Set xlApp = GetObject(,"Excel.Application") Set xlWorkbook = xlApp.ActiveWorkbook 就是你的imageResource并使用lib,例如:imgUrlUniversalImageLoaderVolley ..我们有很多lib支持用url加载图片。

Picasso

答案 3 :(得分:1)

使用此代码下载并在imageView上显示。

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout_here);
        new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
            .execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
    }

    public void onClick(View v) {
        startActivity(new Intent(this, IndexActivity.class));
        finish();
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
}

在AndroidManifest.xml中添加互联网权限。

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

请参阅此link了解更多详情

答案 4 :(得分:1)

当我需要从URL显示图像时,我使用Picasso库。它使用起来非常简单。

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ImageView imageView = (ImageView) view.findViewById(R.id.image);

    Picasso.with(this)
        .load(image_url)
        .into(imageView);
}

您可以看到参考文献和下载库Picasso
希望它有所帮助。

答案 5 :(得分:1)

你应该在onViewCreated()

中调用picdownloadertask
    @Override
            public void onViewCreated(View view, Bundle savedInstanceState) {
                super.onViewCreated(view, savedInstanceState);
                ImageView imageView = (ImageView) view.findViewById(R.id.image);
               new PicDownladerTask().execute(url)


            }

类PicDownloaderTask扩展了AsyncTask {

        @Override
        protected Bitmap doInBackground(String... strings) {
            Bitmap bitmap = getBitmap(strings[0]);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
               BitmapFactory.Options o = new BitmapFactory.Options();
            o.inSampleSize = 4;
            o.inDither = false;
            bitmap = BitmapFactory.decodeResource(getResources(), imageResource, o);
            imageView.setImageBitmap(bitmap);
        }

这是从网址获取图片的方法

 public static Bitmap getBitmap(String url)
    {
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);

            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(70000);
            conn.setReadTimeout(70000);

            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
//            OutputStream os = new FileOutputStream(f);
//            Utils.CopyStream(is, os);
//            os.close();
            bitmap = BitmapFactory.decodeStream(is);
            conn.disconnect();
//            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex){
            ex.printStackTrace();
            if(ex instanceof OutOfMemoryError){}
//                memoryCache.clear();
            return null;
        }
    }

答案 6 :(得分:1)

创建异步任务并在后台执行下载图像

@Override
    protected Bitmap doInBackground(String... url) {
        this.url = url[0];
        final DefaultHttpClient client = new DefaultHttpClient();
        final org.apache.http.client.methods.HttpGet getRequest = new org.apache.http.client.methods.HttpGet(
                url[0]);

        try {
            HttpResponse response = client.execute(getRequest);
            final int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                LoggerUtils.logWarn("ImageDownloader", "Error "
                        + statusCode + " while retrieving bitmap from "
                        + url[0]);
                return null;
            }
            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream inputStream = null;
                try {
                    inputStream = entity.getContent();

                    final Bitmap bitmap = BitmapFactory
                            .decodeStream(inputStream);
                    return bitmap;
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            getRequest.abort();

        }