自定义View和自定义属性的基本步骤:自定义View:
1.创建一个自定义View类:首先,你需要创建一个继承自View或其子类(如ImageView、Button等)的Java类。这个类将代表你的自定义View,并负责绘制和处理用户交互。
2.重写onDraw方法:在自定义View类中,你通常会重写onDraw方法来定义如何绘制你的View。在onDraw方法中,你可以使用Canvas对象进行绘制,绘制各种形状、文本、图像等。
3.处理用户交互:如果需要处理用户交互,你可以重写相应的方法,如onTouchEvent,以响应触摸事件。
项目中有遇到自定义wifi。
直接上代码
kotlin:
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.net.wifi.WifiManager
import android.util.AttributeSet
import android.view.View
import kotlin.math.min
import kotlin.math.sqrt
class WiFiStateView @JvmOverloads constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) :
View(context, attrs, defStyleAttr) {
private var wifi_state = 1
private var height = 0
private var width = 0
private var paint: Paint? = null
private var startAngle = 0
private var sweepAngle = 0
private var wifiHeight = 0
private var padding_bottom = 0
private var bottom_x = 0
private var bottom_y = 0
enum class Style {
RECT, ROUND
}
private var style = Style.ROUND
init {
init()
}
private fun init() {
paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint!!.color = Color.BLACK
paint!!.isAntiAlias = true
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
//获取宽的测量模式
val heightSize = MeasureSpec.getSize(heightMeasureSpec) //测量值
height = resolveSize(heightSize, heightMeasureSpec)
val widthSize = MeasureSpec.getSize(widthMeasureSpec) //测量值
width = resolveSize(widthSize, widthMeasureSpec)
val calc_wifi_height = (width / (sqrt(2.0))).toInt()
wifiHeight = min(calc_wifi_height.toDouble(), height.toDouble()).toInt()
padding_bottom = (height - wifiHeight) / 2
bottom_x = width / 2
bottom_y = height - padd