class CustomView extends View{ Paint paint; public CustomView(Context context) { super(context); paint = new Paint(); paint.setColor(Color.YELLOW); paint.setStrokeJoin(Paint.Join.ROUND); paint.setStrokeCap(Paint.Cap.ROUND); paint.setStrokeWidth(10f); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.RED); canvas.drawLine(10, 10, 100, 100, paint);} }
为什么代码可以运行的 但是画的线没显示
public class CustomView extends View {
Paint paint;
public CustomView(Context context) {
super(context);
init();
}
public void init() {
paint = new Paint();
paint.setColor(Color.YELLOW);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(10f);
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.RED);
canvas.drawLine(10, 10, 100, 100, paint);
}
}
这是自定义view,
然后去你的layout文件夹下的资源文件,比如activity_main.xml,加入你的View
比如:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".demoIntentActivity">
<你项目的包名.CustomView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
你真的确定可以运行??没有bug? 你就重写了一个方法,你就不能多重写几个吗
CustomView(Context context){} 是动态添加时用的方法
CustomView(Context context, @Nullable AttributeSet attrs) {}是写在xml布局文件里调用的方法
如果你想直接写在xml里,请把xml布局文件里调用的方法补全