0

我看到很多关于在适配器中使用 convertView 的有用性的帖子,比如这个这个这个(以及许多其他......)

我有一个 ArrayAdapter,但我从头开始创建视图,使用一个简单的水平线性布局,我在其中添加了一些文本视图。文本视图的数量及其权重取决于列表中的位置。第一行可能有 3 个电视,第二行可能有 7 个电视,第三行可能有 25 个电视,每个电视具有不同的权重,具体取决于数据库。

在这种情况下,因为我不能膨胀任何东西,convertView 包含什么?

我应该使用它吗?如果是,我该怎么办?

编辑:这是我的代码:

@Override
public View getView(final int position, View convertView, ViewGroup parent){
    LinearLayout layout = new LinearLayout(context);
    for (int i = 0; i < totalTVNumber; i++) {
        LifeEvent event = getEventFromDB(cost, position);
        if (event != null) {
            TextView eventTV = event.getTextView(getContext());
            eventTV.setLayoutParams(new LinearLayout.LayoutParams(0, 100, weight));//0 en width sinon weight n'est pas pris en compte !!
            layout.addView(eventTV);
        }
    }
}
4

2 回答 2

2

convertView 包含什么?

它包含View您从头开始创建的过去,该过去已滚出屏幕并可以回收。

我应该使用它吗?

是的,请。

如果是,我该怎么办?

和其他人一样。您直接而不是通过通货膨胀来创建视图这一事实并不重要。

因此,您可以执行以下操作:

class YourAdapter extends ArrayAdapter<Whatever> {
    @Override
    public View getView(int position, View convertView,
                          ViewGroup parent) {
      if (convertView==null) {
        convertView=newView(parent);
      }

      bindView(position, convertView);

      return(convertView);
    }

    private View newView(ViewGroup parent) {
      // create and return your new View
    }

    private void bindView(int position, View row) {
      // populate the widgets of your new or recycled view
    }
  }
于 2016-06-19T19:46:46.347 回答
0

ArrayAdapter 会自动为您回收视图。因此,如果使用 Array Adapter,您无需自行处理。请参考我从 ArrayAdapter.java 中提取的以下代码。你可能会从中得到清晰。

public View getView(int position, View convertView, ViewGroup parent) {
        return createViewFromResource(mInflater, position, convertView, parent, mResource);
    }

    private View createViewFromResource(LayoutInflater inflater, int position, View convertView,
            ViewGroup parent, int resource) {
        View view;
        TextView text;

        if (convertView == null) {
            view = inflater.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;
    }
于 2016-06-19T19:45:51.230 回答