-2

我有一个带有用户照片的列表片段。当我滚动我的列表时,它很慢。然后我异步加载我的照片:

public class UserArrayAdapter extends ArrayAdapter<Friend>{
.
.
.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.list_user, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.label);
    textView.setText(friends.get(position).getName());
    String s = friends.get(position).getName();
    String Contact_Id = friends.get(position).getID();
    new BackgroundLoadPhoto(context, Contact_Id, rowView).execute();

    return rowView;
}

class BackgroundLoadPhoto extends AsyncTask<Void, Void, Void> {
Context mContext;
String Contact_Id;
View rowView;
Bitmap photo;
ImageView profile;
public BackgroundLoadPhoto(Context mContext,String Contact_Id,View rowView){
    this.mContext=mContext;
    this.Contact_Id=Contact_Id;
    this.rowView=rowView;
    profile  = (ImageView)rowView.findViewById(R.id.logo); 
}
@Override
protected void onPostExecute(Void result) {
    //set real user immage
    if(photo!=null){
      profile.setImageBitmap(photo);            
    }
}

@Override
protected void onPreExecute() {
    //set default photo
    profile.setImageResource(R.drawable.search_marker);
}

@Override
protected Void doInBackground(Void... params) {
//get user photo in background
photo=getPhoto(Contact_Id);
return null;
}
private Bitmap getPhoto(String Contact_Id){
    Bitmap my_btmp = null;
    //only if it is a real user..
    if(Contact_Id!="-1"){
        Uri my_contact_Uri = Uri.
                withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(Contact_Id));
        InputStream photo_stream = ContactsContract
                .Contacts.openContactPhotoInputStream(mContext.getContentResolver(),my_contact_Uri);            
        BufferedInputStream buf =new BufferedInputStream(photo_stream);
        my_btmp = BitmapFactory.decodeStream(buf);          
    }
    return my_btmp; 
}
}

现在我可以流畅地滚动我的列表了..但我可以在一段时间后看到照片..我不喜欢!我该怎么办?谢谢!

4

1 回答 1

0

您正在异步加载位图,当您滚动它们时它们还没有准备好,所以一旦它们准备好就可以看到它们。

您可以通过对位图使用内存缓存来提高性能,例如http://developer.android.com/reference/android/util/LruCache.html

看到这个 - https://developers.google.com/events/io/sessions/gooio2012/103/

于 2013-02-10T13:42:29.877 回答