2016-06-10 11 views
0

家伙林加载图像和存在于viewpager的Android Viewpager使用下面的自定义代码加载从资源的20幅图片从SD卡

public class CustomPagerAdapter extends PagerAdapter { 
int[] mResources = { 
     R.drawable.slide1, 
     R.drawable.slide2, 
     R.drawable.slide3, 
     R.drawable.slide4, 
     R.drawable.slide5, 
     R.drawable.slide6, 
     R.drawable.slide7, 
     R.drawable.slide8, 
     R.drawable.slide9, 
     R.drawable.slide10, 
     R.drawable.slide11, 
     R.drawable.slide12, 
     R.drawable.slide13, 
     R.drawable.slide14, 
     R.drawable.slide15, 
     R.drawable.slide16, 
     R.drawable.slide17, 
     R.drawable.slide18, 
     R.drawable.slide19, 
     R.drawable.slide20, 


}; 
Context mContext; 
LayoutInflater mLayoutInflater; 

public CustomPagerAdapter(Context context) { 
    mContext = context; 
    mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
} 

@Override 
public int getCount() { 
    return mResources.length; 
} 

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

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

    ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView); 
    imageView.setImageResource(mResources[position]); 

    container.addView(itemView); 

    return itemView; 
} 

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

这工作得很好,但我想把JPG文件在目录上该设备,以便它们可以更改,而无需重新编译应用程序

我想我需要将图像放入mResource数组中。我可以得到的路径,但不知道什么格式的代码应该是,而不是使用可绘制的线

我已阅读文章在这里,但没有任何意义,我对我来说真的很新,代码看起来没有什么我正在使用的代码

任何人都可以指向正确的方向吗?

任何帮助是极大的赞赏

马克

回答

1

是的,你当然可以这样做。我会尽量解释你的过程中一步一步,

步骤1

有一个File对象指向的路径一样,

File directory = new File("path-to-directory"); 

确保路径是与图像的目录,

步骤2

页列出所有使用listFiles()方法目录内的文件,如

File[] allImages = directory.listFiles(); 

现在你把所有的文件,就像int[] mResources的数组。唯一的区别是,现在你有实际的文件引用,而以前你有资源ID。

步骤3

你可以只显示在ViewPager图像,就像你以前一样。但这是一个有点棘手,并可能需要相当多的时间和代码才能从文件中正确显示图像。

您还需要照顾缓存,以便当您再次加载之前加载的映像时,它会从缓存中获取它。

要做到这一点,我建议您使用此库(由Google推荐),Glide

设置的图像是一行代码,

Glide.with(context).from(file).into(imageView); 

就是这样。现在,您的图像将显示在设备目录中的ViewPager中。

+0

感谢您的帮助,但我不想使用任何外部库,必须有一种方法来在纯代码中执行此操作 –

+0

感谢您的帮助本文有一些修改后的答案http://stackoverflow.com/questions/ 32110977 /加载图像,从-SD卡到viewpager,机器人 –