开始学习自定义view的写法,首先新建一个类CircleView继承自View类,完成三类带参构造器,重写ondraw方法,在布局文件中加入自定义view控件,Run之后出现Binary XML file line #:error inflating class XXX错误,原因是没有加入xmlns:custom="http://schemas.android.com/apk/res/com.ryg.chapter_2.viewtext3
这属于是一种约束,规定xml中有哪些元素和他们的关系,需要在布局中添加进去,下面是代码
public class CircleView extends View {
private int mColor = Color.RED;
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public CircleView(Context context){
super(context);
init();
}
public CircleView(Context context, AttributeSet attrs){
super(context,attrs);
init();
}
public CircleView(Context context, AttributeSet attrs,int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
mPaint.setColor(mColor);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int radius = Math.min(width,height) / 2;
canvas.drawCircle(width / 2,height / 2, radius, mPaint);
}
}<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/com.ryg.chapter_2.viewtext3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<com.ryg.chapter_2.viewtext3.CircleView
android:id="@+id/circleView1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#000000" />
</LinearLayout>
本文详细介绍了如何在Android中自定义View,并通过XML约束实现特定样式和功能,解决布局显示问题。
3763

被折叠的 条评论
为什么被折叠?



