Java 具有图像的ListView非常慢
我有一个Java 具有图像的ListView非常慢,java,android,performance,android-listview,bitmap,Java,Android,Performance,Android Listview,Bitmap,我有一个列表视图,它显示一个图像视图,向用户显示相册艺术和两个相册和艺术家的文本视图 然而,当我上下滚动时,它总是非常慢 public class DSongListAdapter extends ArrayAdapter<Song> { Context mContext; List<Song> mObjects; public DSongListAdapter(Context context, List<Song> songLis
列表视图
,它显示一个图像视图
,向用户显示相册艺术和两个相册和艺术家的文本视图
然而,当我上下滚动时,它总是非常慢
public class DSongListAdapter extends ArrayAdapter<Song> {
Context mContext;
List<Song> mObjects;
public DSongListAdapter(Context context, List<Song> songList ) {
super(context, R.layout.list_item_song, songList );
this.mContext = context;
this.mObjects = songList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if( convertView == null ){
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_song, parent, false);
holder.titleLabel = (TextView) convertView.findViewById(R.id.titleLabel);
holder.artistLabel = (TextView) convertView.findViewById(R.id.artistLabel);
holder.cover = (ImageView) convertView.findViewById(R.id.list_image);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.titleLabel.setText( mObjects.get(position).getTitle() );
holder.artistLabel.setText( mObjects.get(position).getArtist() );
Bitmap bm = SongManager.loadBitmap(mContext, mObjects.get(position).getAlbumId() );
if( bm == null )
holder.cover.setImageDrawable( mContext.getResources().getDrawable(R.drawable.untitled) );
else
holder.cover.setImageBitmap(bm);
return convertView;
}
class ViewHolder {
TextView titleLabel;
TextView artistLabel;
ImageView cover;
}
}
每次调用getView()
时,都要执行IPC和间接磁盘I/O。如果您使用Traceview,您会确定这是您的困难的根源
请考虑使用一个类似于异步加载这些图像并缓存它们的库。还有许多其他类似的库——请参见中的“图像加载程序”和“图像视图”类别。
您不应该在ui线程上执行I/O操作。与此相反,您应该以异步方式加载图像。幸运的是,有很多好的库可以这样做。只需查看这一个,它易于使用和自定义:您的图像的大小/分辨率是多少?loadBitmap()
看起来像什么?它是缓存已经加载的映像,还是每次都从磁盘重新加载映像?当您使用Traceview确定问题所在时,您学到了什么?当您启用StrictMode
查看您是否在主应用程序线程上执行网络或磁盘I/O时,您学到了什么?@CraigOtis不知道。这些图像位于我的设备上的mp3文件中。每次都会从磁盘重新加载它们,因为我不知道如何缓存它们。这就是您的loadBitmap()
方法的全部内容吗?你似乎从来没有给位图bm分配过任何东西。很抱歉,复制失败:p我发布了完整的代码。谢谢!!它起作用了!它甚至将内存从42mb减少到25mb。
public static Bitmap loadBitmap( Context c, int album_id ){
Bitmap bm = null;
try {
final Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri,
album_id);
ParcelFileDescriptor pfd = c.getContentResolver()
.openFileDescriptor(uri, "r");
if (pfd != null) {
FileDescriptor fd = pfd.getFileDescriptor();
bm = BitmapFactory.decodeFileDescriptor(fd);
}
} catch (Exception e) {
}
return bm;
}