我按照這個教程http://mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizontal-view-paging/如何縮小ViewPager Android中使用的圖像?
我有一個看起來像這樣的代碼(代碼如下),我得到一個錯誤,說我的圖片太大。 (java.lang.OutOfMemoryError:位圖大小超過虛擬機預算)
我知道很多人問過這個問題,我搜索了很多解決方案。但是,我似乎無法正確運行它。我是新人,希望能在這裏得到一些答案,因爲我不知道我該怎麼做。
位圖解碼是針對圖像的,但是如果我的圖像位於下面的佈局中,該怎麼辦?我如何縮小我的圖像?
public class TutorialPagerAdapter extends PagerAdapter {
Activity activity;
int imageArray[];
private Resources resource;
private class MyPagerAdapter extends PagerAdapter {
public int getCount() {
return 5;
}
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.farleft;
try{
mImageView = (ImageView) collection.findViewById(R.id.tutorial);
mImageView.setImageBitmap(decodeSampledBitmapFromResource(activity.getResources(), R.id.tutorial, 100, 100));
}
catch (NullPointerException e)
{
e.printStackTrace();
}
break;
case 1:
resId = R.layout.left;
break;
case 2:
resId = R.layout.middle;
break;
case 3:
resId = R.layout.right;
break;
case 4:
resId = R.layout.farright;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
public static Bitmap decodeSampledBitmapFromResource(String res, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(res, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(res, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height/(float)reqHeight);
} else {
inSampleSize = Math.round((float)width/(float)reqWidth);
}
}
return inSampleSize;}
}
編輯
我試圖mImageView.setImageBitmap(decodeSampledBitmapFromResource...)
但我得到空指針異常,在這條線。
我試過這個人使用的方法,但它似乎沒有工作。我試過'mImageView.setImageBitmap(decodeSampledBitmapFromResource ...)',但是我得到了NullPointerException。而且我在每個佈局中實際上都有2個圖像。總共有9個佈局。 –
你的代碼在該行有錯誤 – urveshpatel50
mImageView.setImageBitmap(decodeSampledBitmapFromResource(activity.getResources(),R.drawable.ic_launcher,100,100));替換它 – urveshpatel50