[android]自定义组件及其内组件大小的正确设置
一、自定义组件大小的设置
不管你怎么设置,自定义组件似乎总是match_parent。我们需要覆盖onMeasure方法,并在其内正确设置组件大小。
[java]
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//注意:为尽可能简洁本文只讨论EXACTLY和AT_MOST模式
int mode = MeasureSpec.getMode(widthMeasureSpec);
if(mode == MeasureSpec.AT_MOST || mode == MeasureSpec.EXACTLY) {
this.widthMeasureSpec = widthMeasureSpec;
this.heightMeasureSpec = heightMeasureSpec;
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
} else if(mode == MeasureSpec.UNSPECIFIED) {
Log.d("WOGU", "mode=UNSPECIFIED");
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
二、自定义组件内的组件的大小设置
除了覆盖onMeasure还需覆盖onLayout,在其内设置子元素的大小。
[java]
public class MyViewGroup extends ViewGroup {
protected int widthMeasureSpec, heightMeasureSpec;
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if(changed) {
View view = getChildAt(0);
//measure将触发View的onMeasure。
//widthMeasureSpec包括尺寸和模式
//int width = MeasureSpec.getSize(widthMeasureSpec);
//int height = MeasureSpec.getSize(heightMeasureSpec);
//int mode = MeasureSpec.getMode(widthMeasureSpec);
//mode的可能值MeasureSpec.AT_MOST,MeasureSpec.EXACTLY,MeasureSpec.UNSPECIFIED
//这里只是简单的在onMeasure中记录widthMeasureSpec和heightMeasureSpec
//其实MeasureSpec提供了根据sizet和模式合成widthMeasureSpec,heightMeasureSpec的方法
//int widthMeasureSpec = MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY);
//int heightMeasureSpec = MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);
view.layout(0, 0, getWidth(), getHeight());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
this.widthMeasureSpec = widthMeasureSpec;
this.heightMeasureSpec = heightMeasureSpec;
...
}
}
补充:移动开发 , Android ,