我有一个用户照片的listfragment。当我滚动我的列表时,它很慢。然后我加载我的照片异步:
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;
}
}
现在我可以滚动我的列表流利..但我可以看一段时间后的照片..我不喜欢!我该怎么办?谢谢!
答案 0 :(得分:0)
你正在异步加载位图,当你滚动时它们尚未准备就绪,所以你可以在它们准备好后看到它们。
您可以使用位图的内存缓存来提高性能,例如http://developer.android.com/reference/android/util/LruCache.html
请参阅此内容 - https://developers.google.com/events/io/sessions/gooio2012/103/