将图像从SD卡加载到ViewPager Android

时间:2015-08-20 06:28:03

标签: android android-viewpager android-sdcard

我需要将SD卡中文件夹中的图像加载到ViewPager中。这就是我到目前为止所掌握的。

public Drawable getImageFromSdCard(String imageName) {
    Drawable d = null;
    try {
        String path = Environment.getExternalStorageDirectory().toString()
                + "/YourSubDirectory/";
        Bitmap bitmap = BitmapFactory.decodeFile(path + "/" + imageName
                + ".png");
        d = new BitmapDrawable(bitmap);
    } catch (IllegalArgumentException e) {
        // TODO: handle exception
    }
    return d;

}

如何将其设置为ViewPager?

1 个答案:

答案 0 :(得分:1)

您需要使用make适配器扩展PagerAdapter,然后将适配器设置为查看寻呼机

尝试以下代码:

ViewPager mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new TouchImageAdapter());

TouchImageAdapter类:

class TouchImageAdapter extends PagerAdapter {


        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public View instantiateItem(ViewGroup container, int position) {
            ImageView img = new ImageView(container.getContext());
            img.setImageDrawable(getImageFromSdCard(filename));
            container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            return img;
        }

        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

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

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


    }

以下是适配器类

中使用的方法
public Drawable getImageFromSdCard(String imageName) {
    Drawable d = null;
    try {
        String path = Environment.getExternalStorageDirectory().toString()
                + "/YourSubDirectory/";
        Bitmap bitmap = BitmapFactory.decodeFile(path + "/" + imageName
                + ".png");
        d = new BitmapDrawable(bitmap);
    } catch (IllegalArgumentException e) {
        // TODO: handle exception
    }
    return d;

}

希望这有帮助!