说到获取view的大小,一般想到使用View中的getWidht和getHeight,getMeasuredWidth和getMeasuredHeight。但是这几个方法一般都是在view的onlayout的方法执行以后才能进行获得的,如onlayout方法没有执行此时我们应该怎么来获得view的大小呢?
将view.onmeasure(0,0)设置为0的时候表示,此时不需要考虑父控件的布局问题,直接使用getMeasuredWidth和getMeasuredHeight获取此view的自身的实际大小,可以看下面的例子:这个是在网上引用的一段代码
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
下面来说说onMeasure方法:onMeasure方法是父控件在调用子控件的时候,会想子空间传递两个参数——widthMeasureSpec和heightMeasureSpec,来指明控件可以获得的大小参数,然后可以将此参数设置到view的setMeasuredDimension方法中;注意在计算父控件传递过来的--widthMeasureSpec和heightMeasureSpec参数的时候需要首先获得参数的Mode类型即AT_MOST(最大空间),EXACTLY(实际空间)和UNSPECIFIED;
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredHeight = measureHeight(heightMeasureSpec); int measuredWidth = measureWidth(widthMeasureSpec); setMeasuredDimension(measuredHeight, measuredWidth); private int measureHeight(int measureSpec) { // Return measured widget height. } private int measureWidth(int measureSpec) { // Return measured widget width. ; } 边界参数——widthMeasureSpec和heightMeasureSpec ,效率的原因以整数的方式传入。在它们使用之前,首先要做的是使用MeasureSpec类的静态方法getMode和getSize来译解,如下面的片段所示: int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec);
private int measureHeight(int measureSpec) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); // Default size if no limits are specified. int result = 500; if (specMode == MeasureSpec.AT_MOST) { // Calculate the ideal size of your // control within this maximum size. // If your control fills the available // space return the outer bound. result = specSize; } else if (specMode == MeasureSpec.EXACTLY) { // If your control can fit within these bounds return that value. result = specSize; } return result; } private int measureWidth(int measureSpec) { int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); // Default size if no limits are specified. int result = 500; if (specMode == MeasureSpec.AT_MOST) { // Calculate the ideal size of your control // within this maximum size. // If your control fills the available space // return the outer bound. result = specSize; } else if (specMode == MeasureSpec.EXACTLY) // If your control can fit within these bounds return that value. result = specSize; } return result; } 以上的代码摘抄自网络
说道onmeasure方法,在我们有时候进行自定义的空间的时候需要使用此方法对空间的大小进行设定,记住在设置大小的时候一定要加上setMeasuredDimension(measuredHeight, measuredWidth)方法,否则会报错