我正在使用gridView,它显示从assests文件夹加载的图像。
gridview显示来自资产的50多个图像,但该gridview的性能非常差并且滚动时间滞后。
示例代码为:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ameme);
GridView myGallery = (GridView) findViewById(R.id.gridView1);
mBitArray = new Bitmap[5];
//This is just a sample code
try
{
//these images are stored in the root of "assets"
mBitArray[0] = getBitmapFromAsset("AM0.jpg");
mBitArray[1] = getBitmapFromAsset("AM1.jpg");
mBitArray[2] = getBitmapFromAsset("AM2.jpg");
mBitArray[3] = getBitmapFromAsset("AM3.jpg");
mBitArray[4] = getBitmapFromAsset("AM4.jpg");
}
catch (IOException e)
{
e.printStackTrace();
}
myGallery.setAdapter(new GalleryAdapter(this, mBitArray));
}
public class GalleryAdapter extends BaseAdapter
{
private Context mContext;
private Bitmap[] mImageArray;
public GalleryAdapter(Context context, Bitmap[] imgArray)
{
mContext = context;
mImageArray = imgArray;
}
public int getCount()
{
return mImageArray.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
final ImageView imgView = new ImageView(mContext);
imgView.setImageBitmap(mImageArray[position]);
final RelativeLayout borderImg = new RelativeLayout(mContext);
borderImg.setPadding(8, 8, 8, 8);
borderImg.setGravity(Gravity.CENTER | Gravity.BOTTOM);
borderImg.setBackgroundColor(Color.rgb(7,35,63));
borderImg.addView(imgView);
imgView.setLayoutParams(new RelativeLayout.LayoutParams(100,100));
return borderImg;
}
}
private Bitmap getBitmapFromAsset(String strName) throws IOException
{
AssetManager assetManager = getAssets();
InputStream istr = assetManager.open(strName);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
istr.close();
return bitmap;
}
}
如何滚动gridView()
更顺畅?
答案 0 :(得分:0)
ConvertView包含循环视图。你应该检查它是否为null。如果它不为null,则可以再次重用前一行。希望这段代码有所改进。还有一种称为ViewHolder
模式的模式很有用,但不适用于您的情况。
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView == null){
final ImageView imgView = new ImageView(mContext);
final RelativeLayout borderImg = new RelativeLayout(mContext);
imgView.setLayoutParams(new RelativeLayout.LayoutParams(100,100));
borderImg.setPadding(8, 8, 8, 8);
borderImg.setGravity(Gravity.CENTER | Gravity.BOTTOM);
borderImg.setBackgroundColor(Color.rgb(7,35,63));
borderImg.addView(imgView);
convertView.setTag(borderImg);
}else{
borderImg = (RelativeLayout)convertView.getTag();
}
imgView.setImageBitmap(mImageArray[position]);
return borderImg;
}
此外,我猜位图可能很大,请尝试阅读此http://developer.android.com/training/displaying-bitmaps/load-bitmap.html并优化它们。