Search code examples
androidandroid-listviewandroid-cursoradapter

Android Cursor Adapter different layouts


i'm trying to write ListView CursorAdapter with different layouts (2 layouts). I override newView and bindView methods. In pages with identical layouts they work correct, but in pages with mixed app crashes. This occurs because bindView receive view of type list_item_depart at the moment, when must receive list_item_person. (first 2 times inflates list_item_depart and all fine, but 3 element is list_item_person and app crash.

My code:

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View view;
    ViewHolder holder = new ViewHolder();
    if (getItemViewType(cursor) == ContactsDatabaseHelper.TYPE_DEPARTMENT) {
        view = mInflater.inflate(R.layout.list_item_depart, parent, false);
        holder.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        holder.ivFolder = (ImageView) view.findViewById(R.id.ivFolder);
    } else {
        view = mInflater.inflate(R.layout.list_item_person, parent, false);
        holder.tvName = (TextView) view.findViewById(R.id.tvName);
        holder.tvPost = (TextView) view.findViewById(R.id.tvPost);
    }
    view.setTag(holder);
    return view;
}

@Override
public void bindView(View view, Context context, Cursor cursor) {
    ViewHolder holder = (ViewHolder) view.getTag();
    if (getItemViewType(cursor) == ContactsDatabaseHelper.TYPE_DEPARTMENT) {
        int id = cursor.getInt(cursor.getColumnIndex(ContactsDatabaseHelper.DEPART_ID));
        // Department title
        holder.tvTitle.setText(cursor.getString(cursor.getColumnIndex(ContactsDatabaseHelper.DEPART_NAME)));
        // Folder icon
        if (ch.getChildDepartsCountById(id) > 0) {
            holder.ivFolder.setVisibility(View.VISIBLE);
        } else {
            holder.ivFolder.setVisibility(View.GONE);
        }
    } else {
        // Worker name
        holder.tvName.setText(cursor.getString(cursor.getColumnIndex(ContactsDatabaseHelper.EMPLOYEE_NAME)));
        // Worker post
        holder.tvPost.setText(cursor.getString(cursor.getColumnIndex(ContactsDatabaseHelper.EMPLOYEE_TITLE)));
    }
}

Please help, and sorry for my English (thx Google translate)


Solution

  • I do not fully understand why this happens, but when i change overrided method getViewTypeCount() from return 2 to return 3 it's work fine.