自定义View按类型来划分的话,自定义View的实现方式大概可以分为三种:
- 组合控件
- 继承控件
- 自绘控件
上一篇我们讲过了组合控件,接下来我们来讲讲继承控件。
- 继承AppCompatTextView
public class LineTextView extends AppCompatTextView {
private Paint mPaint;
public LineTextView(Context context) {
this(context,null);
}
public LineTextView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public LineTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setColor(Color.BLACK);
}
//重写draw方法,绘制我们需要的中间线以及背景
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
mPaint.setColor(Color.RED);
//绘制方形背景
RectF rectF = new RectF(0,0,width,height);
canvas.drawRect(rectF,mPaint);
mPaint.setColor(Color.WHITE);
//绘制中心曲线,起点坐标(0,height/2),终点坐标(width,height/2)
canvas.drawLine(0,height/2,width,height/2,mPaint);
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.hyq.customviewdome.view.CommonTitleView
android:id="@+id/cTview"
android:layout_width="match_parent"
android:layout_height="50dp"
tools:ignore="MissingConstraints" />
<com.hyq.customviewdome.view.LineTextView
android:id="@+id/lTextView"
android:layout_width="match_parent"
android:layout_height="100dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginTop="80dp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
效果图