私は次のクラスを持っています:
public class MyGridView extends ViewGroup {
...
@Override
public void onSizeChanged(int xNew, int yNew, int xOld, int yOld) {
super.onSizeChanged(xNew, yNew, xOld, yOld);
// do calculations for drawing bounds of child views
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
View child;
Rect rect;
for (int i=0; i < getChildCount(); i++) {
child = getChildAt(i);
rect = getBoundsAtChildIndex(i)
child.layout(rect.left, rect.top, rect.right, rect.bottom);
}
}
...
}
と
public class MyAdapter {
public void setMyGridView(MyGridView myGridView) {
// add a single TextView to my grid view
textView = createTextView(context);
addTextViewToGrid(textView);
container.add(textView);
}
private TextView createTextView(Context context) {
TextView textView = new TextView(context);
textView.setText("1");
textView.setTextColor(0xffffffff);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f);
textView.setTypeface(typeface);
textView.setGravity(Gravity.CENTER | Gravity.FILL);
// textView.setGravity(Gravity.RIGHT); // other tries to see gravity
// textView.setGravity(Gravity.FILL);
return textView;
}
private void addTextViewToGrid(TextView textView) {
myGridViewPtr.addView(textView, ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
}
...
}
カスタム グリッド ビューとアダプターを作成し、その子が画面に正しいサイズと位置に描画されるようにしました。ただし、createTextView() で設定されたそれらの重力は観察されません。
背景画像を textView に設定して、グリッド内のスペースを埋めることができます。
対照的に、textView のテキストは常に左上隅に描画され、Gravity.FILL を使用して収まるように拡大縮小するのではなく、常に 12sp に設定したテキスト サイズのままです。
好ましくは、テキストは、テキストビュー内に収まるようにスケーリングされ、中央に配置されます。
編集
ViewGroup の onMeasure() に次のメソッドを追加しました。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
doUpdateOnSizeChanged(width, height);
for (int i = 0; i < getChildCount(); i++)
getChildAt(i).measure((int) viewDim.x, (int) viewDim.y);
setMeasuredDimension(width, height);
}
子は、互いに同じ高さ、幅であると想定されています。ViewGroup の Android サンプル コードは、必要以上に洗練されています。たとえば、すべての子の幅、高さの最大値を取得していません。
私の onMeasure() の場合、ViewDim の子の幅、高さは、doUpdateOnSizeChanged で計算される幅、高さの整数であり、getMeasuredWidth、getMeasuredHeight よりも小さくなります。
その結果、TextView の左下隅にテキストが配置されます。