2017-02-26 3 views
0

LinearLayout을 확장하는 사용자 정의보기를 만들고 있습니다. 선형 레이아웃에 몇 가지 셰이프를 추가하고 있는데, 현재 이들 사이에 고정 된 값을 사용하고 있습니다. 나는 LayoutParams을 정의하고 여백을 설정하여 도형 사이의 공간을 만듭니다.위젯 너비가 wrap_content로 설정되어 있는지 확인하는 방법

내가하고 싶은 일은 화면의 너비가 match_parent 또는 fill_parent으로 설정된 경우에만 전체 화면의 등 간격으로 화면을 채우므로 채울 것입니다. wrap_content으로 설정하면 원래 고정 된 공간 값을 설정해야합니다.

나는 일을 시도했다 :

@Override 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
{ 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    int parentWidth = MeasureSpec.getSize(widthMeasureSpec); 
    spaceBetweenShapesPixels = (parentWidth - shapeWidth * numberOfShapes)/numberOfShapess; 
} 

그러나, 방법은 두 번 호출 할 것 같다 - 일단 부모의 폭과 높이와 대한 그 후보기의 자체와는 뷰 자체에 대한 때 , 공백은 0 값을 얻습니다.

그래서 난 그냥 할 수있는 방법이 논리는 :

if(width is wrap_content) 
{ 
    space = 10; 
} 
else 
{ 
    space = (parentWidth - shapeWidth * numberOfShapes)/numberOfShapess; 
} 

답변

0

당신은 onMeasure() 방법 WidthModeHeightMode 를 사용해야합니다. 뷰에 관계없이 실제로되고 싶어 얼마나 큰 정확히이 많은 픽셀이어야합니다 - 아래는 내 프로젝트 중 하나

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
int widthMode = MeasureSpec.getMode(widthMeasureSpec); 
int heightMode = MeasureSpec.getMode(heightMeasureSpec); 
int measuredWidth = 0, measuredHeight = 0; 

if (widthMode == MeasureSpec.EXACTLY || widthMode == MeasureSpec.AT_MOST) { 
    measuredWidth = MeasureSpec.getSize(widthMeasureSpec); 
} 

if (heightMode == MeasureSpec.EXACTLY) { 
    measuredHeight = MeasureSpec.getSize(heightMeasureSpec); 
} else if (heightMode == MeasureSpec.AT_MOST) { 
    double height = MeasureSpec.getSize(heightMeasureSpec) * 0.8; 
    measuredHeight = (int) height;// + paddingTop + paddingBottom; 
} 
} 

MeasureSpec.EXACTLY에서 시료 A입니다.

MeasureSpec.AT_MOST -보기가 이보다 작을 수도 있습니다.

MeasureSpec.UNSPECIFIED -보기에는 표시해야하는 콘텐츠를 표시하기 위해 필요한 크기 여야합니다.

은 자세한 내용 https://stackoverflow.com/a/16022982/2809326

+0

나는 그것이 내가 내 질문에 썼다 의사 코드 템플릿에 맞추는 방법을하지 이해하지 못했다이를 참조하십시오. 모드에 기반한 조건은 사용자가 너비를 wrap_content로 설정했음을 의미합니까? –