Android ListView Adapter getView()方法调用多次

时间:2016-07-12 05:33:13

标签: java android listview

Java代码

public class ContentListAdapter extends ArrayAdapter<Content> implements Filterable {

//private static final String TAG = ContentListAdapter.class.getCanonicalName();
private static final LogTracer LOG_TRACER = LogTracer.instance(ContentListAdapter.class);
private Context mContext;
private LayoutInflater mInflater;
private List<Content> mContents;
private List<Content> mContentsFiltered;
private int lastPosition = -1;
private boolean multiselectMode = false;
private Customer mCustomer = null;

private AdapterView.OnItemClickListener mOnItemClickListener;
private AdapterView.OnItemLongClickListener mOnItemLongClickListener;
PatientRatingDAO patientRatingDAO;
int completeVisiblePosition=0;
public int totalScrollCount= 0;
private boolean isFromHomeSearch;
private ListView mListView;
public View helpView;

public ContentListAdapter(Context context, List<Content> contents, ListView listView) {
    super(context, R.layout.list_content, contents);
    mContext = context;
    mContents = contents;
    mListView = listView;
    mContentsFiltered = contents;
    mInflater = LayoutInflater.from(mContext);
    mCustomer = new CustomerDAO(context).getCurrentCustomer();
    patientRatingDAO = new PatientRatingDAO(getContext());

}


private class ViewHolder {
    View listContent;
    ImageButton contentThumbnail, contentThumbnailNew,typeofarticle;
    LinearLayout contentRightSec;
    LinearLayout contentRightSecBottom;
    TextView fileSize;
    LinearLayout tagsView;
    TextView contentPostTime;
    TextView contentDescription;
    TextView contentSource;

    LinearLayout rateCountSec;
    LinearLayout rateBarLayout;
    TextView rateCount;
    TextView likeCount;
    TextView likeText;
    ImageView likeImage,likeCountImage,rateCountImage,readtick;
    RatingBar ratingBar;
    RatingBar disabledRatingBar;
    RelativeLayout patienteducation;
    //int isLiked;
    //int currentUserRateCount;

}



@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
    // assign the view we are converting to a local variable
    View v = convertView;
    LOG_TRACER.d("parm getView " + position + " " + convertView);
    // Calculating Scroll Count
    if(getCompleteVisiblePosition() == 0){
        if(v != null && mListView != null){
            this.setCompleteVisiblePosition(calculateCompletelyVisibleListItems(v));
            LOG_TRACER.d("parm completeVisiblePosition" + completeVisiblePosition);
        }
    }
    if(getCompleteVisiblePosition() > 0){
        if(position % getCompleteVisiblePosition() == 0){
            totalScrollCount++;
            LOG_TRACER.d("parm totalScrollCount" + totalScrollCount);
        }
    }
    // first check to see if the view is null. if so, we have to inflate it.
    // to inflate it basically means to render, or show, the view.
    if (v == null) {
        //LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //v = inflater.inflate(mLayout, null);
        v = LayoutInflater.from(mContext).inflate(R.layout.list_content, parent, false);
        ViewHolder holder = new ViewHolder();

        holder.rateCount = (TextView) v.findViewById(R.id.rateCount);
        holder.likeCount = (TextView) v.findViewById(R.id.likeCount);
        holder.likeCountImage = (ImageView) v.findViewById(R.id.likeCountImage);
        holder.rateCountImage = (ImageView) v.findViewById(R.id.rateCountImage);
        holder.likeText = (TextView) v.findViewById(R.id.like_text);
        holder.likeImage = (ImageView) v.findViewById(R.id.like_image);
        holder.ratingBar = (RatingBar) v.findViewById(R.id.ratingBar);
        holder.disabledRatingBar = (RatingBar) v.findViewById(R.id.disabled_rating_bar);
        holder.typeofarticle = (ImageButton) v.findViewById(R.id.typeofarticle);
        holder.patienteducation = (RelativeLayout) v.findViewById(R.id.patient_education);
        v.setTag(holder);
    }


    final Content content = getItem(position);
    final ViewHolder viewHolder = (ViewHolder) v.getTag();
    if(viewHolder.listContent != null) {
        if(content.getIs_Read() == Constants.INT_FLAG_YES) {
            viewHolder.listContent.setBackgroundResource(R.drawable.list_selector_content_grey);
            viewHolder.readtick.setVisibility(View.VISIBLE);
        } else {
            viewHolder.listContent.setBackgroundResource(R.drawable.list_selector_content_white);
            viewHolder.readtick.setVisibility(View.GONE);
        }


    if(viewHolder.contentThumbnailNew != null){
        Ion.with(viewHolder.contentThumbnailNew).fitXY().placeholder(R.drawable.imagethumbnail).fitXY().error(R.drawable.imagethumbnail).fitXY().load(
                (!TextUtils.isEmpty(content.getDA_Thumbnail_Url()))?content.getDA_Thumbnail_Url().replaceAll(" ","%20") : content.getDA_Thumbnail_Url());
    }

    if(viewHolder.contentThumbnail != null) {
        viewHolder.contentThumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SettingsUtils.getDefaultCompanyId(mContext) == content.getCompany_Id() && !isFromHomeSearch) {
                    if (multiselectMode) {
                        if (mOnItemClickListener != null)
                            mOnItemClickListener.onItemClick(null, v, position, position);
                    } else {
                        if (mOnItemLongClickListener != null)
                            mOnItemLongClickListener.onItemLongClick(null, v, position, position);
                    }
                } else {
                    if (mOnItemClickListener != null)
                        mOnItemClickListener.onItemClick(null, v, position, position);
                }

            }
        });




        viewHolder.contentThumbnailNew.setOnTouchListener(new TouchExtendedClickListener(mContext, new TouchExtendedClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view) {
                if (mOnItemClickListener != null) mOnItemClickListener.onItemClick(null, convertView, position, position);
            }
        }));
        viewHolder.contentThumbnailNew.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (SettingsUtils.getDefaultCompanyId(mContext) == content.getCompany_Id() && !isFromHomeSearch) {
                    if (multiselectMode) {
                        if (mOnItemClickListener != null)
                            mOnItemClickListener.onItemClick(null, v, position, position);
                    } else {
                        if (mOnItemLongClickListener != null)
                            mOnItemLongClickListener.onItemLongClick(null, v, position, position);
                    }
                }
                return true;
            }
        });

        }
    }


    }


    //To Set Ratings
    if (viewHolder.rateCount != null) {
        //Calculate rate count by (totalratigs/numberofusersrated)
        if(content.getTotalRatings() == 0 || content.getTotalRatedCount()==0){
            viewHolder.rateCount.setText("0");
        }else if(content.getTotalRatedCount() != 0){
            viewHolder.rateCount.setText(String.valueOf(Math.round(content.getTotalRatings()/content.getTotalRatedCount())));
        }
    }

    //To Set Likes
    if (viewHolder.likeCount != null) {
        viewHolder.likeCount.setText(String.valueOf(content.getLikes()));
    }

    //if viewHolder.isLiked == 0 then user not yet liked else if viewHolder.isLiked == 1 the user liked
    //viewHolder.isLiked = content.getIsLiked();
    //viewHolder.currentUserRateCount = content.getCurrentUserRateCount();


    //Add Like Listeners
    if (viewHolder.likeText != null && viewHolder.likeImage != null) {

        if(content.getIsLiked() == 0){
            //Set liked image and text
            viewHolder.likeText.setText("Like");
            viewHolder.likeImage.setImageResource(R.drawable.ic_like_grey_24dp);
            viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_grey_24dp);
        }else{
            //Set liked image and text
            //viewHolder.likeText.setText(mContext.getResources().getString(R.string.content_liked));
            viewHolder.likeImage.setImageResource(R.drawable.ic_like_pink_24dp);
            viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_pink_24dp);
        }

        viewHolder.likeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (content.getIsLiked() == 0) {
                    content.setIsLiked(1);


                    //To insert/update user likes to local database
                    PatientRating patientRating = patientRatingDAO.getByDACodeAndType(content.getDA_Code(),content.getContent_Type());
                    if(patientRating != null){
                        patientRating.setIsLiked(content.getIsLiked());
                        patientRatingDAO.update(patientRating);
                    }else{
                        patientRating = new PatientRating();
                        patientRating.setIsLiked(1);
                        patientRating.setContent_Type(content.getContent_Type());
                        patientRating.setDA_Code(content.getDA_Code());
                        patientRatingDAO.insert(patientRating);
                    }

                    //viewHolder.likeText.setText(mContext.getResources().getString(R.string.content_liked));
                    viewHolder.likeImage.setImageResource(R.drawable.ic_like_pink_24dp);
                    viewHolder.likeCountImage.setImageResource(R.drawable.ic_like_pink_24dp);

                    //Increase like counts
                    int likes = 1 + Integer.parseInt(viewHolder.likeCount.getText().toString());
                    viewHolder.likeCount.setText(String.valueOf(likes));
                    viewHolder.rateBarLayout.setVisibility(View.VISIBLE);
                    Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.like_animation);
                    viewHolder.likeImage.startAnimation(animation);
                    //Toast.makeText(mContext, "Liked", Toast.LENGTH_SHORT).show();





    return v;
}

@Override
public int getCount() {
    return mContentsFiltered.size();
}

@Override
public Content getItem(int position) {
    return mContentsFiltered.get(position);
}

public Filter getFilter(FilterOption filterOption) {
    return getFilter();
}

@Override
public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            String filterString = constraint.toString().toLowerCase().trim();

            FilterResults results = new FilterResults();

            final List<Content> list = mContents;

            int count = list.size() - 1;
            List<Content> nlist = new ArrayList<Content>(list.size());

            Content filterableContent;
            for (int i = 0; i <= count; i++) {
                filterableContent = list.get(i);
                if(filterableContent.getDA_Name().toLowerCase().contains(filterString)) {
                    nlist.add(filterableContent);
                } else if (!TextUtils.isEmpty(filterableContent.getTags())
                        && filterableContent.getTags().toLowerCase().contains(filterString)) {
                    nlist.add(filterableContent);
                }else if (!TextUtils.isEmpty(filterableContent.getCompany_Name())
                        && filterableContent.getCompany_Name().toLowerCase().contains(filterString)) {
                    nlist.add(filterableContent);
                }
            }
            /*List<Integer> companyIds = StaticVariableUtils.getFilterOption().getFilterCompanyIds();
            for (int i = 0; i < count; i++) {
                filterableContent = list.get(i);
                if(filterableContent.getDA_Name().toLowerCase().contains(filterString)) {
                    // if company ids are selected, check if
                    // the filtered content has slected company id
                    if(companyIds != null && companyIds.size() >= 1) {
                        if(companyIds.indexOf(filterableContent.getCompany_Id()) >= 0) {
                            nlist.add(filterableContent);
                        }
                    } else {
                        nlist.add(filterableContent);
                    }

                }
            }

            List<Content> tmpList = new ArrayList<>(nlist.size());
            if(nlist != null) {
                // sort by datetime
                Collections.sort(nlist, new Comparator<Content>() {
                    @Override
                    public int compare(Content lhs, Content rhs) {
                        if(StaticVariableUtils.getFilterOption().getSortingOrder() == R.string.sortingOrderLatest) {
                            return (lhs.getUploaded_Date().getTime()>rhs.getUploaded_Date().getTime()
                                    ? -1 : (lhs.getUploaded_Date().getTime()==rhs.getUploaded_Date().getTime() ? 0 : 1));
                        } else {
                            return (lhs.getUploaded_Date().getTime()<rhs.getUploaded_Date().getTime()
                                    ? -1 : (lhs.getUploaded_Date().getTime()==rhs.getUploaded_Date().getTime() ? 0 : 1));
                        }
                    }
                });
            }

            FilterOption filterOption = StaticVariableUtils.getFilterOption();
            if(filterOption.getShowByDate() == R.string.showByDateToday) {
                nlist = filterByToday(nlist);
            } else if(filterOption.getShowByDate() == R.string.showByDateLastWeek) {
                nlist = filterByLastWeek(nlist);
            } else if(filterOption.getShowByDate() == R.string.showByDateTwoWeeks) {
                nlist = filterByTwoWeeks(nlist);
            } else if(filterOption.getShowByDate() == R.string.showByDateThreeWeeks) {
                nlist = filterByThreeWeeks(nlist);
            } else if(filterOption.getShowByDate() == R.string.showByDateLastMonth) {
                nlist = filterByLastMonth(nlist);
            } else if(filterOption.getShowByDate() == R.string.showByDateOlder) {
                nlist = filterByOlder(nlist);
            }

            if(filterOption.getShowByStatus() != R.string.showByStatusAll) {
                nlist = getReadOrUnread(nlist, filterOption.getShowByStatus());
            }*/

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            mContentsFiltered = (ArrayList<Content>) results.values;
            notifyDataSetChanged();
        }
    };
}

我的xml文件

            <ListView
            android:id="@+id/lvContent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#e2e2e2"
            android:clipToPadding="false"
            android:divider="@null"
            android:dividerHeight="0dp"
            android:fadingEdge="none"
            android:smoothScrollbar="true"
            android:fitsSystemWindows="true"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            android:scrollbarStyle="insideOverlay">

        </ListView>
列表视图的适配器中的

getView方法在位置0多次调用 所以花了更多的时间加载这个Activity.This代码我正在使用....我不知道为什么getview()调用多次。我的工作代码在上面...如何解决这个问题

1 个答案:

答案 0 :(得分:0)

I Resolve this issuee...... Because i added list from three different methods and also set notifydatasetchange. so my get view called more than one time....