问题描述
- android 自定义控件 onMeasure
-
android 自定义控件SurfaceView@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int originalWidth = MeasureSpec.getSize(widthMeasureSpec);//800
int calculatedHeight = originalWidth * aspectHeight / aspectWidth;//1095
super.onMeasure(
MeasureSpec.makeMeasureSpec(originalWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(calculatedHeight, MeasureSpec.EXACTLY));
}对onMeasure方法表示不理解, 上述代码中的originalWidth,calculatedHeight,是指控件本身还是真个屏幕?通过debug,发现打印出来的值都对不上啊? <view android:layout_width="wrap_content" android:layout_height="wrap_content" class="com.sensetime.facesign.util.DefinedSurfaceView" android:id="@+id/surfaceView" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> package com.sensetime.facesign.util;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.SurfaceView;import com.sensetime.facesign.R;
/**
- Created by SenseTime on 2015/1/10.
*/
public class DefinedSurfaceView extends SurfaceView {private int aspectWidth = 480;
private int aspectHeight = 640;
private Context mContext;public DefinedSurfaceView(Context context) {
super(context);
mContext = context;
}public DefinedSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setCustomAttributes(attrs);
}public DefinedSurfaceView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContext = context;
setCustomAttributes(attrs);
}private void setCustomAttributes(AttributeSet attrs) {
TypedArray a = mContext.obtainStyledAttributes(attrs,
R.styleable.definedlayout);
aspectWidth = a.getDimensionPixelSize(
R.styleable.definedlayout_target_width, 480);//aspectWidth == 480 //??
aspectHeight = a.getDimensionPixelSize(
R.styleable.definedlayout_target_height, 640);//aspectHeight == 640 //??}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int originalWidth = MeasureSpec.getSize(widthMeasureSpec);//800
int calculatedHeight = originalWidth * aspectHeight / aspectWidth;//1095
super.onMeasure(
MeasureSpec.makeMeasureSpec(originalWidth, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(calculatedHeight, MeasureSpec.EXACTLY));
}
}
- Created by SenseTime on 2015/1/10.
解决方案
Android 自定义控件onMeasure()方法详解
自定义控件---onMeasure和onLayout
解决方案二:
如果是SurfaceView,则不能根据 onMeasure获取高宽
需要用
SurfaceHolder.Callback的surfaceCreated才能获取实际的高度和宽度
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.d("TEST","Width="+ this.getWidth()+"|Height="+this.getHeight());
}
view可以用onMeasure