39

Android のリストビューで効率を最大化するには、画面に収まるのに必要な数の膨張した「行」ビューのみを使用する必要があることを学びました。ビューが画面外に移動したら、getViewメソッドでそれを再利用して、convertViewが null かどうかを確認する必要があります。

ただし、リストに 2 つの異なるレイアウトが必要な場合、このアイデアをどのように実装できますか? 注文のリストで、1 つのレイアウトが完了した注文用で、もう 1 つのレイアウトが処理中の注文用であるとします。

これは、私のコードが使用しているアイデアのチュートリアルの例です。私の場合、次の 2 行のレイアウトがR.layout.listview_item_product_completeあります。R.layout.listview_item_product_inprocess

public View getView(int position, View convertView, ViewGroup parent) {

ViewHolder holder = null;

if (convertView == null) {
    holder = new ViewHolder();
    if(getItemViewType(position) == COMPLETE_TYPE_INDEX) {
        convertView = mInflator.inflate(R.layout.listview_item_product_complete, null);
        holder.mNameTextView = (TextView) convertView.findViewById(R.list.text_complete);
        holder.mImgImageView = (ImageView) convertView.findViewById(R.list.img_complete);
    }
    else { // must be INPROCESS_TYPE_INDEX
        convertView = mInflator.inflate(R.layout.listview_item_product_inprocess, null);
        holder.mNameTextView = (TextView) convertView.findViewById(R.list.text_inprocess);
        holder.mImgImageView = (ImageView) convertView.findViewById(R.list.img_inprocess);
    }
    convertView.setTag(holder);
} else {
    holder = (ViewHolder) convertView.getTag();
}
    thisOrder = (Order) myOrders.getOrderList().get(position);
    // If using different views for each type, use an if statement to test for type, like above
    holder.mNameTextView.setText(thisOrder.getNameValue());
    holder.mImgImageView.setImageResource(thisOrder.getIconValue());
    return convertView;
}

public static class ViewHolder {
    public TextView mNameTextView;
    public ImageView mImgImageView;
}
4

2 に答える 2

84

アダプターのビュー リサイクラーに、複数のレイアウトが存在することと、行ごとに 2 つのレイアウトを区別する方法を知らせる必要があります。これらのメソッドをオーバーライドするだけです:

@Override
public int getItemViewType(int position) {
    // Define a way to determine which layout to use, here it's just evens and odds.
    return position % 2;
}

@Override
public int getViewTypeCount() {
    return 2; // Count of different layouts
}

次のように、getItemViewType()内部に組み込みます。getView()

if (convertView == null) {
    // You can move this line into your constructor, the inflater service won't change.
    mInflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    if(getItemViewType(position) == 0)
        convertView = mInflater.inflate(R.layout.listview_item_product_complete, parent, false);
    else
        convertView = mInflater.inflate(R.layout.listview_item_product_inprocess, parent, false);
    // etc, etc...

Android の Romain Guyが Google Talks でビュー リサイクラについて話しているのをご覧ください。

于 2012-11-08T20:33:15.663 に答える
9
于 2012-11-08T20:34:49.890 に答える