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;
            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.dateView.setText(Utility.getFriendlyDayString(context, cursor.getLong(ForecastFragment.COL_WEATHER_DATE)));

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

        ViewHolder(View view) {
            iconView = ((ImageView) view.findViewById(;
            dateView = ((TextView) view.findViewById(;

No comments:

Post a Comment