ListView Customization & Optimization

Customization to handle Multiple/Different types of Rows/Views in a single ListView:

Use getViewTypeCount(), getItemViewType(), newView() to inflate/create different types of views based on the given position of row.


ViewHolder optimization:

Since list view reuses the objects used in rows, newView() should use findViewById(), save views in a custom ViewHolder object & do setTag(). Then bindView() can simply use getTag() to fetch the view objects and directly use setText() etc to set the contents to be shown. Alternatively, if applicable, The views can be directly saved as members in onCreateView() and utilized in onLoadFinished().


Both are shown in code below:
    static final int VIEW_TYPE_TODAY  = 0;
    static final int VIEW_TYPE_FUTURE = 1;
    static final int VIEW_TYPE_COUNT = 2;
    public int getViewTypeCount() {
        return VIEW_TYPE_COUNT;
    }

    public int getItemViewType(int position) {
        return (0 == position) ? VIEW_TYPE_TODAY : VIEW_TYPE_FUTURE;
    }

    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        if (VIEW_TYPE_TODAY == getItemViewType(cursor.getPosition()))
            layoutId = R.layout.list_item_forecast_today;
        else
            layoutId = R.layout.list_item_forecast;
        view = LayoutInflater.from(context).inflate(layoutId, parent, false);
        view.setTag(new ViewHolder(view));
        return view;
    }

    public void bindView(View view, Context context, Cursor cursor) {
        holder = (ViewHolder) view.getTag();
        holder.iconView.setImageResource(R.mipmap.ic_launcher);
        holder.dateView.setText(Utility.getFriendlyDayString(context, cursor.getLong(ForecastFragment.COL_WEATHER_DATE)));
        holder.descView.setText(cursor.getString(ForecastFragment.COL_WEATHER_DESC));
    }

    class ViewHolder {
        public final ImageView iconView;
        public final TextView dateView;

        ViewHolder(View view) {
            iconView = ((ImageView) view.findViewById(R.id.list_item_icon));
            dateView = ((TextView) view.findViewById(R.id.list_item_date_textview));
        }
    }









No comments:

Post a Comment