使用asynctask加载图像时Android listview中的奇怪行为

使用asynctask加载图像时Android listview中的奇怪行为,android,listview,android-listview,android-asynctask,Android,Listview,Android Listview,Android Asynctask,我希望任何人都能帮我解决我遇到的ListView问题。昨天我一直把头撞在铁墙上,因为我不知道问题出在哪里。让事情变得更难的不是我的项目 我有一个列表视图,我想在其中加载联系人行。在每行的左侧,我想(向下)加载一个异步图像。为此,我使用以下ArrayAdapter和ListItem布局,请忽略不推荐使用的函数 这是一段视频 问题: 每当列表加载时,所有图像都会相互加载,然后放置在正确的位置。它看起来真的很油滑,尽管它反应很快,而且看起来很可怕。我在arrayadapter中添加了一个计数器来计算调

我希望任何人都能帮我解决我遇到的ListView问题。昨天我一直把头撞在铁墙上,因为我不知道问题出在哪里。让事情变得更难的不是我的项目

我有一个列表视图,我想在其中加载联系人行。在每行的左侧,我想(向下)加载一个异步图像。为此,我使用以下ArrayAdapter和ListItem布局,请忽略不推荐使用的函数

这是一段视频

问题: 每当列表加载时,所有图像都会相互加载,然后放置在正确的位置。它看起来真的很油滑,尽管它反应很快,而且看起来很可怕。我在arrayadapter中添加了一个计数器来计算调用getView的次数

  • 4个没有异步映像的项目-大约38次
  • 4个带有异步映像的项目-大约180次
希望有人能帮助我

ArrayAdapter

    public class ChatContactListArrayAdapter extends ArrayAdapter<ChatContact>{

    private Context context;
    private ArrayList<ChatContact> chatContacts;

    public static DiskImageLoaderHelper diskImageLoader;

    public int count = 0;

    public ChatContactListArrayAdapter(Context context, int resource, ArrayList<ChatContact> chatContacts) {
        super(context, resource, chatContacts);

        this.chatContacts = chatContacts;
        this.context = context;
        diskImageLoader = new DiskImageLoaderHelper(context, "ChatListImages", (1024 * 1024 * 10), CompressFormat.JPEG, 90);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        count++;
        Log.e(DebugHelper.TAG_DEBUG, "Count: " + count + " Position: " + position);
        ChatContact chatContact = chatContacts.get(position);

        View view = convertView;

        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.chat_contact_list_row, null);
        }

        ImageView contactImageView = (ImageView) view.findViewById(R.id.contact_image);
        if (chatContact.Picture != null) {
            BitmapWorkerTask bitmapWorker = new BitmapWorkerTask(contactImageView, diskImageLoader);
            bitmapWorker.execute(chatContact.Picture);
        } else {
            contactImageView.setVisibility(View.INVISIBLE);
        }

        TextView fromTextView = (TextView) view.findViewById(R.id.fromName);
        fromTextView.setText(chatContact.Name);

        Boolean l_blToMe = false;
        if (chatContact.From == chatContact.Id) {
            l_blToMe = true;
        }

        LinearLayout chatContactRow = (LinearLayout) view.findViewById(R.id.chatContactRow);
        ImageView imageViewStatusMessage = (ImageView) view.findViewById(R.id.lastMessageStatusImg);

        TextView lastMessage = (TextView) view.findViewById(R.id.lastMessage);
        if (CommonUtilities.isNullOrEmpty(chatContact.Message) && !CommonUtilities.isNullOrEmpty(chatContact.MessageId)) {
            lastMessage.setText("<afbeelding>");
        } else {
            lastMessage.setText(chatContact.Message);
        }

        imageViewStatusMessage.setImageResource(0);

        if (!CommonUtilities.isNullOrEmpty(chatContact.Received)) {
            imageViewStatusMessage.setImageDrawable(context.getResources().getDrawable(R.drawable.chat_double_check));
            chatContactRow.setBackgroundColor(Color.parseColor("#F2F2F2"));
            lastMessage.setTypeface(null, Typeface.NORMAL);
        } else if (!CommonUtilities.isNullOrEmpty(chatContact.Sent) && !l_blToMe) {
            imageViewStatusMessage.setImageDrawable(context.getResources().getDrawable(R.drawable.chat_single_check));
            chatContactRow.setBackgroundColor(Color.parseColor("#F2F2F2"));
            lastMessage.setTypeface(null, Typeface.NORMAL);
        } else if (!CommonUtilities.isNullOrEmpty(chatContact.Sent) && l_blToMe) {
            imageViewStatusMessage.setImageDrawable(context.getResources().getDrawable(R.drawable.chat_arrow));
            chatContactRow.setBackgroundColor(Color.parseColor("#F4E0CC"));
            lastMessage.setTypeface(null, Typeface.BOLD);
        } else {
            imageViewStatusMessage.setVisibility(View.INVISIBLE);
        }

        TextView receivedDate = (TextView) view.findViewById(R.id.receivedDate);

        if (!CommonUtilities.isNullOrEmpty(chatContact.Sent) && CommonUtilities.isNullOrEmpty(chatContact.Received)) {
            try {
                SimpleDateFormat l_dbDateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
                Date l_dOrgDate = (Date) l_dbDateFormatter.parse(chatContact.Sent);
                SimpleDateFormat l_showDateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm");

                String newDateStr = l_showDateFormatter.format(l_dOrgDate);
                receivedDate.setText(newDateStr);
            } catch (ParseException e) {
                Log.e(DebugHelper.TAG_ERROR, "ChatContactListAdapter::" + e.toString());
//              ACRA.getErrorReporter().handleSilentException(e);
            }
        } else if (!CommonUtilities.isNullOrEmpty(chatContact.Received)) {
            try {
                SimpleDateFormat l_dbDateFormatter = new SimpleDateFormat(
                        "yyyyMMddHHmmss");
                Date l_dOrgDate = (Date) l_dbDateFormatter.parse(chatContact.Received);
                SimpleDateFormat l_showDateFormatter = new SimpleDateFormat(
                        "dd-MM-yyyy HH:mm");

                String newDateStr = l_showDateFormatter.format(l_dOrgDate);
                receivedDate.setText(newDateStr);
            } catch (ParseException e) {
                Log.e(DebugHelper.TAG_ERROR, "ChatContactListAdapter::" + e.toString());
//              ACRA.getErrorReporter().handleSilentException(e);
            }
        } else {
            receivedDate.setVisibility(View.INVISIBLE);
        }

        return view;
    }

    @Override
    public void clear() {
        count = 0;
        super.clear();
    }

    class BitmapWorkerTask extends AsyncTask<String, Void, Drawable> {

        private final WeakReference<ImageView> contactImageView;
        private DiskImageLoaderHelper diskImageLoader;

        public BitmapWorkerTask(ImageView imageView, DiskImageLoaderHelper diskImageLoader) {
            this.contactImageView = new WeakReference<ImageView>(imageView);
            this.diskImageLoader = diskImageLoader;
        }

        @Override
        protected Drawable doInBackground(String... params) {
            String imageUrl = params[0];
            Bitmap bitmap = null;
            if (!diskImageLoader.containsKey(CommonUtilities.filePathToCacheKey(imageUrl, false)) || false) {
                bitmap = CommonUtilities.getCroppedBitmap(CommonUtilities.createBitmapFromImageLocation(CommonUtilities.mStrBasePath + imageUrl), 50);
                if(bitmap != null) {
                    diskImageLoader.put(CommonUtilities.filePathToCacheKey(imageUrl, true), bitmap);
                }
            } else {
                bitmap = diskImageLoader.getBitmap(CommonUtilities.filePathToCacheKey(imageUrl, false));
            }

            return new BitmapDrawable(context.getResources(), bitmap);
        }

        @Override
        protected void onPostExecute(Drawable drawable) {
            ImageView view = contactImageView.get();
            if (view != null && drawable != null) {
                view.setBackgroundDrawable(drawable);
//              contactImageView.setImageBitmap(bitmap);
                view.setImageDrawable(context.getResources().getDrawable(R.drawable.image_round_overlay_grey));
            }
        }
    }
}
公共类ChatContactListArrayAdapter扩展了ArrayAdapter{
私人语境;
私人ArrayList聊天室联系人;
公共静态diskImageLoader帮助每个diskImageLoader;
公共整数计数=0;
公共ChatContactListArrayAdapter(上下文上下文、int资源、ArrayList chatContacts){
超级(上下文、资源、聊天联系人);
this.chatContacts=chatContacts;
this.context=上下文;
diskImageLoader=新的DiskImageLoaderHelper(上下文,“ChatListImages”(1024*1024*10),CompressFormat.JPEG,90);
}
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
计数++;
Log.e(DebugHelper.TAG_DEBUG,“计数:+Count+”位置:+Position);
ChatContact ChatContact=chatContacts.get(位置);
视图=转换视图;
如果(视图==null){
LayoutInflater充气器=(LayoutInflater)getContext().getSystemService(Context.LAYOUT\u充气器\u SERVICE);
视图=充气机。充气(R.layout.chat\u contact\u list\u row,空);
}
ImageView contactImageView=(ImageView)view.findViewById(R.id.contact\u image);
如果(chatContact.Picture!=null){
BitmapWorkerTask bitmapWorker=新的BitmapWorkerTask(contactImageView,diskImageLoader);
执行(chatContact.Picture);
}否则{
contactImageView.setVisibility(视图.不可见);
}
TextView fromTextView=(TextView)view.findViewById(R.id.fromName);
fromTextView.setText(chatContact.Name);
布尔l_blToMe=false;
if(chatContact.From==chatContact.Id){
l_blToMe=真;
}
LinearLayout chatContactRow=(LinearLayout)view.findViewById(R.id.chatContactRow);
ImageView imageViewStatusMessage=(ImageView)view.findViewById(R.id.lastMessageStatusImg);
TextView lastMessage=(TextView)view.findViewById(R.id.lastMessage);
if(CommonUtilities.isNullOrEmpty(chatContact.Message)和&!CommonUtilities.isNullOrEmpty(chatContact.MessageId)){
lastMessage.setText(“”);
}否则{
lastMessage.setText(chatContact.Message);
}
imageViewStatusMessage.setImageResource(0);
如果(!CommonUtilities.isNullOrEmpty(chatContact.Received)){
imageViewStatusMessage.setImageDrawable(context.getResources().getDrawable(R.drawable.chat_double_check));
chatContactRow.setBackgroundColor(Color.parseColor(“#f2f2”);
lastMessage.setTypeface(null,Typeface.NORMAL);
}如果(!CommonUtilities.isNullOrEmpty(chatContact.Sent)和&!l_blToMe),则为else{
imageViewStatusMessage.setImageDrawable(context.getResources().getDrawable(R.drawable.chat_single_check));
chatContactRow.setBackgroundColor(Color.parseColor(“#f2f2”);
lastMessage.setTypeface(null,Typeface.NORMAL);
}如果(!CommonUtilities.isNullOrEmpty(chatContact.Sent)和&l_blToMe),则为else{
imageViewStatusMessage.setImageDrawable(context.getResources().getDrawable(R.drawable.chat_箭头));
chatContactRow.setBackgroundColor(Color.parseColor(“#F4E0CC”);
lastMessage.setTypeface(null,Typeface.BOLD);
}否则{
imageViewStatusMessage.setVisibility(视图不可见);
}
TextView receivedDate=(TextView)view.findViewById(R.id.receivedDate);
if(!CommonUtilities.isNullOrEmpty(chatContact.Sent)和&CommonUtilities.isNullOrEmpty(chatContact.Received)){
试一试{
SimpleDataFormat l_dbDateFormatter=新的SimpleDataFormat(“yyyyMMddHHmmss”);
Date l_dOrgDate=(Date)l_dbDateFormatter.parse(chatContact.Sent);
SimpleDateFormat l_showDateFormatter=新的SimpleDateFormat(“dd-MM-yyy-HH:MM”);
字符串newDateStr=l_showDateFormatter.format(l_dOrgDate);
receivedDate.setText(newDateStr);
}捕获(解析异常){
Log.e(DebugHelper.TAG_错误,“ChatContactListAdapter::”+e.toString());
//ACRA.getErrorReporter().handleSilentException(e);
}
}如果(!CommonUtilities.isNullOrEmpty(chatContact.Received))为else{
试一试{
SimpleDataFormat l_dbDateFormatter=新SimpleDataFormat(
“yyyyMMddHHmmss”);
Date l_dOrgDate=(Date)l_dbDateFormatter.parse(chatContact.Received);
SimpleDataFormat l_showDateFormatter=新SimpleDataFormat(
“dd-MM-yyy-HH:MM”);
字符串newDateStr=l_showDateFormatter.format(l_dOrgDate);
receivedDate.setText(newDateStr);
}捕获(解析异常){
Log.e(DebugHelper.TAG_错误,“ChatContactListAdapter::”+e.toString());
//ACRA.getErrorReporter().handleSilentExc
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/chat_contact_list_selector"
    android:orientation="horizontal"
    android:id="@+id/chatContactRow" >

    <ImageView
        android:id="@+id/contact_image"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"
        android:src="@drawable/image_round_overlay_grey"/>

    <LinearLayout
        android:id="@+id/TextualHolder"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" 
        android:baselineAligned="false">

        <RelativeLayout 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" 
            android:baselineAligned="false">
            <TextView
                android:id="@+id/fromName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dip"
                android:layout_marginTop="10dp"
                android:paddingBottom="10dip"
                android:textColor="#222222"
                android:ellipsize="end"
                android:singleLine="true"
                android:textSize="18sp" />

            <TextView
                android:id="@+id/receivedDate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="15dp"
                android:layout_marginTop="10dp"
                android:layout_alignParentRight="true"
                android:paddingBottom="10dip"
                android:textColor="#777777"
                android:textSize="10sp"
                android:textStyle="bold" />
        </RelativeLayout>

        <LinearLayout
            android:id="@+id/statusMessageHolder"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginLeft="10dip"
            android:paddingBottom="10dip" >

            <ImageView
                android:id="@+id/lastMessageStatusImg"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical" />

            <TextView
                android:id="@+id/lastMessage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#777777"
                android:textSize="15sp"
                android:ellipsize="end"
                android:singleLine="true"
                android:textStyle="bold"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        context = getActivity().getApplicationContext();

        mLvContactList = (ListView) getView().findViewById(R.id.listContacts);
        if(mDbDataBase == null)
            mDbDataBase = nl.w3s.hulpverlener.JohelpenApplication.mDbDataBase;
        if(mCurDB == null)
            mCurDB = nl.w3s.hulpverlener.JohelpenApplication.mCurDB;

        mCursor = mCurDB.query(mTblChatContacts.mTable, mDbDataBase.dbFieldsToString(mTblChatContacts.mFields), null, null, null, null, null);
        chatContacts = CommonUtilities.getContactsFromCursor(mCursor);
        mCursor.close();

        chatContactArrayAdapter = new ChatContactListArrayAdapter(getActivity(), R.layout.chat_contact_list_row, chatContacts);
        mLvContactList.setAdapter(chatContactArrayAdapter);

        mLvContactList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent,
                            final View view, int position, long id) {

                        ChatContact chatContact = (ChatContact) parent.getItemAtPosition(position);
                        ChatFragment chatFragment = new ChatFragment(chatContact.Id);
                        mMainObject.switchContent(chatFragment, true);
                    }
                });

        getSherlockActivity().getSupportActionBar().setIcon(R.drawable.icon_ab_chat);
        getSherlockActivity().getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        MainActivity.mMenuLayout = -1;
        getSherlockActivity().invalidateOptionsMenu();
        setStatusMessage();

        mMainObject.setTitle(mTitle);
    }
if (chatContact.Picture != null) {
        BitmapWorkerTask bitmapWorker = new BitmapWorkerTask(contactImageView, diskImageLoader);
        bitmapWorker.execute(chatContact.Picture);
}
else
{
        contactImageView.setImageResource(R.id.icon); // only for your reference.. add default image
} 
 View view = convertView;

 if (view == null) {
     LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     view = inflater.inflate(R.layout.chat_contact_list_row, null);
 }
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.chat_contact_list_row, null);