Generalmente durante la creazione di un layout personalizzato che estende View
o ViewGroup
, è necessario sostituire protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
e protected void onLayout(boolean changed, int left, int top, int right, int bottom)
. Questi sono chiamati durante il processo di inflazione al fine di ottenere le dimensioni e le informazioni sulla posizione relative alla vista. Inoltre, successivamente, se si estende ViewGroup
, è necessario chiamare measure(int widthMeasureSpec, int heightMeasureSpec)
e layout(int l, int t, int r, int b)
su ogni vista secondaria contenuta all'interno. (measure() viene chiamato in onMeasure() e layout() viene chiamato in onLayout()).
Ad ogni modo, in onMeasure()
, generalmente si fa qualcosa del genere.
@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 ***
}
In onLayout()
si ottenere le coordinate effettive pixel della vista, in modo da poter ottenere la dimensione fisica in questo modo:
@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;
}
L'ho usato per qualche tempo per regolare il testo in textview, non sapevo che potesse essere usato anche per ViewGroup. Grazie per l'aiuto! – PravinCG