问题描述
自定义视图:
class BarView : View {
private var mBarPaint = Paint(ANTI_ALIAS_FLAG)
private var mBarWidthRatio = 0f
private var mBarColor = Color.BLACK
var barWidthRatio
get() = mBarWidthRatio
set(value) {
mBarWidthRatio = value
invalidate()
}
var barColor
get() = mBarColor
set(value) {
mBarColor = value
invalidate()
}
constructor(context: Context) : super(context)
constructor(context: Context,attrs: AttributeSet) : super(context,attrs) {
context.obtainStyledAttributes(attrs,R.styleable.BarView).apply {
mBarWidthRatio = getFloat(R.styleable.BarView_barColor,0f)
mBarColor = getColor(R.styleable.BarView_barWidthRatio,0)
recycle()
}
}
override fun onDraw(canvas: Canvas) {
mBarPaint.color = mBarColor
canvas.drawRect(0f,0f,width * mBarWidthRatio,height.toFloat(),mBarPaint)
}
}
可设置样式的资源:
<resources>
<declare-styleable name="BarView">
<attr name="barColor" format="color" />
<attr name="barWidthRatio" format="float" />
</declare-styleable>
</resources>
活动XML:
<?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:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="134dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.example.barchart2.BarView
android:id="@+id/bar"
android:layout_width="200dp"
android:layout_height="50dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/guideline"
app:layout_constraintTop_toTopOf="parent"
app:barWidthRatio="0.75" />
</androidx.constraintlayout.widget.ConstraintLayout>
活动类别:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bar.setBackgroundColor(-10000)
button.setOnClickListener() {
println("Width: " + bar.width)
println("Height: " + bar.height)
println("Left: " + bar.left)
println("Top: " + bar.top)
println("Right: " + bar.right)
println("Bottom: " + bar.bottom)
}
}
}
我收到以下错误:
“无法启动活动ComponentInfo {com.example.barchart2 / com.example.barchart2.MainActivity}:android.view.InflateException:二进制XML文件第28行:二进制XML文件第28行:膨胀类com时出错。 example.barchart2.BarView“
它使用整数或字符串资源,但不使用浮点数或分数。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)