通常、View
またはViewGroup
に拡張されたカスタムレイアウトを作成するときは、protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
とprotected void onLayout(boolean changed, int left, int top, int right, int bottom)
を上書きする必要があります。これらは、ビューに関連するサイズと位置情報を取得するために、インフレーションの処理中に呼び出されます。また、その後、ViewGroup
を延長する場合は、内に含まれるすべての子ビューでmeasure(int widthMeasureSpec, int heightMeasureSpec)
とlayout(int l, int t, int r, int b)
を呼び出す必要があります。 (measure()はonMeasure()で呼び出され、layout()はonLayout()で呼び出されます)。
とにかく、onMeasure()
には、このようなことが一般的です。 onLayout()
で
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// Gather this view's specs that were passed to it
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int chosenWidth = DEFAULT_WIDTH;
int chosenHeight = DEFAULT_HEIGHT;
if(widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.EXACTLY)
chosenWidth = widthSize;
if(heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.EXACTLY)
chosenHeight = heightSize;
setMeasuredDimension(chosenWidth, chosenHeight);
*** NOW YOU KNOW THE DIMENSIONS OF THE LAYOUT ***
}
あなたがそうのような物理的なサイズ得ることができるので、あなたは、ビューの実際のピクセル座標を取得する:私が正しくあなたの要件を理解していれば、OnGlobalLayoutListenerはあなたに何を与える可能性があり
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom)
{
// Android coordinate system starts from the top-left
int width = right - left;
int height = bottom - top;
}
私はこれをtextviewizeで調整するためにこれを使用してきましたが、ViewGroupでもこれを使うことはできませんでした。助けてくれてありがとう! – PravinCG