44

この前の人のように、GridView アイテム間に不要な重複があります。

GridView アイテムの重なり

一番右の列を除くすべての列のテキストに注目してください。

前の質問と私が違うところは、一定の行の高さを望んでいないということです。画面スペースを効率的に使用するために、各行の最も高いコンテンツに対応するように行の高さを変更したいと考えています。

GridViewのソース(信頼できるコピーではありませんが、kernel.org はまだダウンしています) を見ると、fillDown() と makeRow() で、最後に表示されたビューが「参照ビュー」であることがわかります。行の高さは次の場所から設定されます。最も高いものからではなく、そのビューの高さ。これは、右端の列が問題ない理由を説明しています。残念ながら、継承によってこれを修正するには、GridView が適切に設定されていません。関連するすべてのフィールドとメソッドは非公開です。

では、「クローンして所有する」という使い古された肥大化した道をたどる前に、ここで見逃しているトリックはありますか? TableLayout を使用することもできますが、それにはnumColumns="auto_fit"自分で実装する必要があり (たとえば、電話画面に長い列が 1 つだけ必要なため)、それは AdapterView にもなりません。

編集:実際、クローンと所有はここでは実用的ではありません。GridView は、その親クラスと兄弟クラスのアクセスできない部分に依存しているため、少なくとも 6000 行のコード (AbsListView、AdapterView など) をインポートすることになります。

4

6 に答える 6

26

行の最大高さを駆動するために静的配列を使用しました。セルが再表示されるまで以前の列のサイズが変更されないため、これは完全ではありません。インフレートされた再利用可能なコンテンツ ビューのコードを次に示します。

編集:この作業は正しく行われましたが、レンダリングする前にすべてのセルを事前に測定しました。これを行うには、GridView をサブクラス化し、onLayout メソッドに測定フックを追加しました。

/**
 * Custom view group that shares a common max height
 * @author Chase Colburn
 */
public class GridViewItemLayout extends LinearLayout {

    // Array of max cell heights for each row
    private static int[] mMaxRowHeight;

    // The number of columns in the grid view
    private static int mNumColumns;

    // The position of the view cell
    private int mPosition;

    // Public constructor
    public GridViewItemLayout(Context context) {
        super(context);
    }

    // Public constructor
    public GridViewItemLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Set the position of the view cell
     * @param position
     */
    public void setPosition(int position) {
        mPosition = position;
    }

    /**
     * Set the number of columns and item count in order to accurately store the
     * max height for each row. This must be called whenever there is a change to the layout
     * or content data.
     * 
     * @param numColumns
     * @param itemCount
     */
    public static void initItemLayout(int numColumns, int itemCount) {
        mNumColumns = numColumns;
        mMaxRowHeight = new int[itemCount];
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // Do not calculate max height if column count is only one
        if(mNumColumns <= 1 || mMaxRowHeight == null) {
            return;
        }

        // Get the current view cell index for the grid row
        int rowIndex = mPosition / mNumColumns;
        // Get the measured height for this layout
        int measuredHeight = getMeasuredHeight();
        // If the current height is larger than previous measurements, update the array
        if(measuredHeight > mMaxRowHeight[rowIndex]) {
            mMaxRowHeight[rowIndex] = measuredHeight;
        }
        // Update the dimensions of the layout to reflect the max height
        setMeasuredDimension(getMeasuredWidth(), mMaxRowHeight[rowIndex]);
    }
}

BaseAdapter サブクラスの測定関数を次に示します。updateItemDisplayビューセルに適切なすべてのテキストと画像を設定するメソッドがあることに注意してください。

    /**
     * Run a pass through each item and force a measure to determine the max height for each row
     */
    public void measureItems(int columnWidth) {
        // Obtain system inflater
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        // Inflate temp layout object for measuring
        GridViewItemLayout itemView = (GridViewItemLayout)inflater.inflate(R.layout.list_confirm_item, null);

        // Create measuring specs
        int widthMeasureSpec = MeasureSpec.makeMeasureSpec(columnWidth, MeasureSpec.EXACTLY);
        int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);

        // Loop through each data object
        for(int index = 0; index < mItems.size(); index++) {
            String[] item = mItems.get(index);

            // Set position and data
            itemView.setPosition(index);
            itemView.updateItemDisplay(item, mLanguage);

            // Force measuring
            itemView.requestLayout();
            itemView.measure(widthMeasureSpec, heightMeasureSpec);
        }
    }

最後に、レイアウト中にビュー セルを測定するように設定された GridView サブクラスを次に示します。

/**
 * Custom subclass of grid view to measure all view cells
 * in order to determine the max height of the row
 * 
 * @author Chase Colburn
 */
public class AutoMeasureGridView extends GridView {

    public AutoMeasureGridView(Context context) {
        super(context);
    }

    public AutoMeasureGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public AutoMeasureGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if(changed) {
            CustomAdapter adapter = (CustomAdapter)getAdapter();

            int numColumns = getContext().getResources().getInteger(R.integer.list_num_columns);
            GridViewItemLayout.initItemLayout(numColumns, adapter.getCount());

            if(numColumns > 1) {
                int columnWidth = getMeasuredWidth() / numColumns;
                adapter.measureItems(columnWidth);
            }
        }
        super.onLayout(changed, l, t, r, b);
    }
}

リソースとして列の数を持っている理由は、向きなどに基づいて異なる数を持つことができるようにするためです.

于 2011-09-27T11:17:39.760 に答える
1

Chris からの情報に基づいて、他の GridView アイテムの高さを決定するときにネイティブ GridView で使用される参照ビューを利用して、この回避策を使用しました。

この GridViewItemContainer カスタム クラスを作成しました。

/**
 * This class makes sure that all items in a GridView row are of the same height.
 * (Could extend FrameLayout, LinearLayout etc as well, RelativeLayout was just my choice here)
 * @author Anton Spaans
 *
*/
public class GridViewItemContainer extends RelativeLayout {
private View[] viewsInRow;

public GridViewItemContainer(Context context) {
    super(context);
}

public GridViewItemContainer(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public GridViewItemContainer(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void setViewsInRow(View[] viewsInRow) {
    if  (viewsInRow != null) {
        if (this.viewsInRow == null) {
            this.viewsInRow = Arrays.copyOf(viewsInRow, viewsInRow.length);
        }
        else {
            System.arraycopy(viewsInRow, 0, this.viewsInRow, 0, viewsInRow.length);
        }
    }
    else if (this.viewsInRow != null){
        Arrays.fill(this.viewsInRow, null);
    }
}

@Override
protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    if (viewsInRow == null) {
        return;
    }

    int measuredHeight = getMeasuredHeight();
    int maxHeight      = measuredHeight;
    for (View siblingInRow : viewsInRow) {
        if  (siblingInRow != null) {
            maxHeight = Math.max(maxHeight, siblingInRow.getMeasuredHeight());
        }
    }

    if (maxHeight == measuredHeight) {
        return;
    }

    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    switch(heightMode) {
    case MeasureSpec.AT_MOST:
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(maxHeight, heightSize), MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        break;

    case MeasureSpec.EXACTLY:
        // No debate here. Final measuring already took place. That's it.
        break;

    case MeasureSpec.UNSPECIFIED:
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        break;

    }
}

アダプターのgetViewメソッドで、 convertViewを新しい GridViewItemContainer の子としてラップするか、これをアイテム レイアウトの最上位の XML 要素にします。

        // convertView has been just been inflated or came from getView parameter.
        if (!(convertView instanceof GridViewItemContainer)) {
            ViewGroup container = new GridViewItemContainer(inflater.getContext());

            // If you have tags, move them to the new top element. E.g.:
            container.setTag(convertView.getTag());
            convertView.setTag(null);

            container.addView(convertView);
            convertView = container;
        }
        ...
        ...
        viewsInRow[position % numColumns] = convertView;
        GridViewItemContainer referenceView = (GridViewItemContainer)convertView;
        if ((position % numColumns == (numColumns-1)) || (position == getCount()-1)) {
            referenceView.setViewsInRow(viewsInRow);
        }
        else {
            referenceView.setViewsInRow(null);
        }

ここで、numColumns は GridView 内の列の数であり、'viewsInRow' は、'position' が配置されている現在の行のビューのリストです。

于 2012-12-21T17:08:29.000 に答える
0

これは、以下で説明する正しい解決策ではありませんが、要件によっては回避策になる可能性があります。

ラップできるように、グリッドビューの子レイアウトからビュー修正の高さを設定するだけです(一部のdp、つまり50dp)。

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:ellipsize="end"
            android:textColor="@color/text_color"
            android:textSize="13dp"
            android:textStyle="normal" />
于 2021-03-30T07:06:07.910 に答える
-2

GridView に重みを与えると、LinearLayouts 内の GridViews が子として機能します。このように、GridView はビューポートをその子で満たすので、アイテムが画面に収まる限り (スクロールすると)、そのアイテムを表示できます。

ただし、ScrollViews 内で GridViews を使用することは常に避けてください。それ以外の場合は、各子供の身長を計算し、チェイスが上記で回答したように再割り当てする必要があります。

<GridView
    android:id="@+id/gvFriends"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:verticalSpacing="5dp"
    android:horizontalSpacing="5dp"
    android:clipChildren="false"
    android:listSelector="@android:color/transparent"
    android:scrollbarAlwaysDrawHorizontalTrack="false"
    android:scrollbarAlwaysDrawVerticalTrack="false"
    android:stretchMode="columnWidth"
    android:scrollbars="none"
    android:numColumns="4"/>
于 2014-11-05T13:03:11.697 に答える