0

I'm trying to implement the ViewHolder pattern with convertView. Two questions:

1) When I comment lines #1 and #2 (which are required for the pattern) everything works fine. When the if is in place everything gets scrambled, the first element of the list gets shown twice (in the beginning and in the end of the list) and after some orientation changes and list scrolling everything gets jumbled. Why is this happenning?

2) I'm using a ListActivity and providing the TextView and array of Strings for the ArrayAdapter (#3) but for some reason I still need line (#4) otherwise the list items are blank. Is this because i'm not using super.getView()?

class SushiAdapter extends ArrayAdapter<String> {

    private final Activity context;

    SushiAdapter(Activity context) {
        super(context, R.layout.row, R.id.label, MenuItems); // #3
        this.context = context;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
                View row = convertView;
                if (row == null) { //#1
                    LayoutInflater inflater = context.getLayoutInflater();
                    row = inflater.inflate(R.layout.row, parent, false);
                    ViewHolder holder = new ViewHolder();
                    holder.icon = (ImageView) row.findViewById(R.id.icon);
                    holder.position = position;
                    holder.item = (TextView) row.findViewById(R.id.label);
                    row.setTag(holder);
                } // #2
                ViewHolder newHolder = (ViewHolder) row.getTag();
                newHolder.item.setText(MenuItems[newHolder.position]); // #4
                newHolder.icon.setImageResource(R.drawable.sushi);
                return row;
    }           
}
4

1 回答 1

0

If you are creating a new instance of array adapter, for example:

ArrayAdapter<T> sushiAdapter = new ArrayAdapter<T>(context, R.layout.row, R.id.label, MenuItems)

this instance already has it's own implementation of getView method. So it's obvious that in your case when override getView, you provide the complete implementation by yourself and take all responsibilities for filling views with content. So if you want to add add something new, please call super.getView() before.

But in your case, when you have Image + text view you need to extend BaseAdapter and provide all implementation by yourself. ArrayAdapter provides simple functionality and extending it is not a common practice.

于 2013-06-11T21:07:06.617 回答