重点
怎么自定义控件,Canvas画布,Paint画笔,Path路径的使用
首先为什么要自定义View:
在Android开发中有很多业务场景,原生的控件是无法满足应用,并且经常也会遇到一个UI在多处重复使用情况,那么就需要通过自定义View的方式来实现这些UI效果。
作为一个Android开发工程师,自定义view时一个必备的技能
Android定义View有几种方式
自定义View的实现方式有以下几种:组合控件,继承控件,自绘控件
详细可分为:自定义组合控件,继承系统View控件,继承系统ViewGroup,自绘View控件,自绘 ViewGroup控件
自定义组合控件的使用步骤
1.编写布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="@+id/rl"
android:background="@color/teal_200"
>
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="10dp"
android:background="@drawable/ic_baseline_arrow_back_24" />
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="微信"
android:textSize="24sp"
android:textColor="@color/white"
android:layout_centerInParent="true"/>
</RelativeLayout>
2.创建自定义View类并继承View(要自定义的View)并实现构造方法
public class HeaderView extends RelativeLayout {
private RelativeLayout rl;
private ImageView iv;
private TextView tv;
public HeaderView(Context context) {
super(context);
}
public HeaderView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HeaderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public HeaderView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
}
3.初始化UI
public HeaderView(Context context, AttributeSet attrs) {
super(context, attrs);
initview(context);
}
private void initview(Context context) {
LayoutInflater.from(context).inflate(R.layout.view_head,this,true);
rl=findViewById(R.id.rl);
iv=findViewById(R.id.iv);
tv=findViewById(R.id.tv);
}<