在自定义View的时候,发现不执行onDraw方法,在网上查了方法,
1.在构造方法里增加setWillNotDraw(false)方法,发现不起作用.
2.主动的调用invalidate();方法,也不起作用,
经过查找发现了下面的问题.特此记录下来,希望可以帮助到大家.
1.自定义的View所在的布局中,自定义View计算不出位置.
2.确定不了View宽和高
3.在onMeasure()方法中没设置控件的宽和高
public class TempView extends View {
private final String TAG = TempView.class.getSimpleName();
public TempView(Context context) {
this(context, null);
}
public TempView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
Log.d(TAG, "--TempView--");
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d(TAG, "--onMeasure--");
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
Log.d(TAG, "--onLayout--");
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d(TAG, "--onDraw--");
}
就是自定义View所在的是在NestedScrollView中
打印出日志
2019-02-18 10:40:34.801 17499-17499/demo.tx.com.buttondemo D/TempView: --TempView--
2019-02-18 10:40:34.848 17499-17499/demo.tx.com.buttondemo D/TempView: --onMeasure--
2019-02-18 10:40:34.866 17499-17499/demo.tx.com.buttondemo D/TempView: --onMeasure--
2019-02-18 10:40:34.868 17499-17499/demo.tx.com.buttondemo D/TempView: --onLayout--
从日志中中可以看出没有执行onDraw方法,原因就是自定义View计算不出位置.
将NestedScrollView改为LinearLayout
2019-02-18 10:44:37.989 17863-17863/demo.tx.com.buttondemo D/TempView: --TempView--
2019-02-18 10:44:38.029 17863-17863/demo.tx.com.buttondemo D/TempView: --onMeasure--
2019-02-18 10:44:38.048 17863-17863/demo.tx.com.buttondemo D/TempView: --onMeasure--
2019-02-18 10:44:38.050 17863-17863/demo.tx.com.buttondemo D/TempView: --onLayout--
2019-02-18 10:44:38.073 17863-17863/demo.tx.com.buttondemo D/TempView: --onDraw--
就是给自定义View设置固定的高和宽
打印日志
2019-02-18 10:47:05.148 18012-18012/demo.tx.com.buttondemo D/TempView: --TempView--
2019-02-18 10:47:05.193 18012-18012/demo.tx.com.buttondemo D/TempView: --onMeasure--
2019-02-18 10:47:05.211 18012-18012/demo.tx.com.buttondemo D/TempView: --onMeasure--
2019-02-18 10:47:05.213 18012-18012/demo.tx.com.buttondemo D/TempView: --onLayout--
2019-02-18 10:47:05.239 18012-18012/demo.tx.com.buttondemo D/TempView: --onDraw--
在onMeasure方法中设置控件的宽和高
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(width,height);
Log.d(TAG, "onMeasure");
}