自定义View,和Canvas(画布),Paint(画笔),Path(路径)的用法

本文介绍了在Android开发中自定义控件的重要性,并详细阐述了自定义组合控件的实现步骤,包括布局文件的编写、自定义View类的创建、初始化UI、提供对外方法等。同时,探讨了继承View类和ViewGroup类来创建系统控件的方法。此外,文章还深入讲解了Canvas、Paint和Path这三个绘图工具类的用法,Canvas作为画布,Paint用于设置绘制风格,而Path则用于描点和连线。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

重点

        怎么自定义控件,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);
    }<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值