ArrayAdapter中的getView

来源:互联网 发布:java手动线程池使用 编辑:程序博客网 时间:2024/05/01 15:57

摘要: 我曾想利用ArrayAdapter中的getView来获取ListView中每个item的View对象。结果是,无论我怎么对View对象进行更改都不产生影响。不会变是理所当然,因为getView,其实是”createView“。
我曾想利用ArrayAdapter中的getView来获取ListView中每个item的View对象。结果是,无论我怎么对View对象进行更改都不产生影响。不会变是理所当然的,因为getView,其实是”createView“。下面是我参考的源代码:

 public View getView(int position, View convertView, ViewGroup parent) {        return createViewFromResource(position, convertView, parent, mResource);    }    private View createViewFromResource(int position, View convertView, ViewGroup parent,            int resource) {        View view;        TextView text;        if (convertView == null) {            view = mInflater.inflate(resource, parent, false);        } else {            view = convertView;        }        try {            if (mFieldId == 0) {                //  If no custom field is assigned, assume the whole resource is a TextView                text = (TextView) view;            } else {                //  Otherwise, find the TextView field within the layout                text = (TextView) view.findViewById(mFieldId);            }        } catch (ClassCastException e) {            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");            throw new IllegalStateException(                    "ArrayAdapter requires the resource ID to be a TextView", e);        }        T item = getItem(position);        if (item instanceof CharSequence) {            text.setText((CharSequence)item);        } else {            text.setText(item.toString());        }        return view;    }
从代码来看,肯定不可能是我所想的那样。如果convertView等于null,每次调用getView都是返回一个新的对象。但是,为什么呢?我的理解是,Adapter作为Controller,向下从Model层中获取数据,向上向View层提供对象。作为给予者,不应该了解View层的信息。所以,通过Adapter来获取View层的对象,这本身就是不可取的。

转载自:https://my.oschina.net/u/582355/blog/356838

public abstract View getView (int position, View convertView, ViewGroup parent)
Since: API Level 1
Get a View that displays the data at the specified position in the data set. You can either create a View manually or inflate it from an XML layout file. When the View is inflated, the parent View (GridView, ListView…) will apply default layout parameters unless you use inflate(int, android.view.ViewGroup, boolean) to specify a root view and to prevent attachment to the root.
Parameters

①position : The position of the item within the adapter’s data set of the item whose view we want.
②convertView : The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view.
③parent : The parent that this view will eventually be attached to

Returns
* A View corresponding to the data at the specified position.

0 0
原创粉丝点击