سؤال

I'm facing some trouble with the navigation drawer adapter. It's supposed to display items as follows: Favorito, Categorias, and small sub categories underneath categorias.

I programmed the navigation drawer adapter to use a big_layout.xml file by default, but if its position is greater than a certain value, then it uses a small_layout.xml file.

It works fine for the first few items, but the problem is when I scroll down to see the rest of the items, they use the big_layout.xml, and then when I scroll back up, the original big items change their view and use the small layout!

below is the code, and this is a screen shot of the bad results: http://i.stack.imgur.com/QWwts.jpg

    @Override
public View getView(int position, View view, ViewGroup parent) {
    if (view == null) {
        LayoutInflater laoutInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        if (getItemId(position)>3)
            view = laoutInflater.inflate(R.layout.drawer_list_item_small, null);
        if (getItemId(position)<=3)
            view = laoutInflater.inflate(R.layout.drawer_list_item, null);
    }

    ImageView icon = (ImageView) view.findViewById(R.id.icon);
    icon.setImageResource(drawerItems.get(position).getIcon());        
    TextView title = (TextView) view.findViewById(R.id.title);
    title.setText(drawerItems.get(position).getTitle());
    return view;}

Is there anything wrong I'm doing ? , Is there something missing that might be responsible of making the view stable?

How can i fix this ?

هل كانت مفيدة؟

المحلول

Your issue is with recycling. When you scroll down and back up, the views using the small layout are no longer needed, and so are eligible for recycling - now, the view is not null, so the layout will not be reinitialised based on its position, but merely updated with the new content.

You can fix this by using ViewTypes in your list adapter class, overriding the following methods.

@Override
public int getItemViewType(int position) {
    return (position > 3) ? 0 : 1;
}

@Override
public int getViewTypeCount() {
    return 2;
}

Then, in your getView() you will not be given a view (for recycling) if it is of the wrong view type.

@Override
public View getView(int position, View view, ViewGroup parent) {
    if (view == null) {
        int layout = getLayoutForViewType(position);
        view = LayoutInflater.from(parent.getContext()).inflate(layout, null);
    }
    ...
    return view;
}

private int getLayoutForViewType(int position) {
    if (getItemViewType(position) == 0) {
        return R.layout.blahblahblah;
    }
    return R.layout.bloobloobloo;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top