【发布时间】:2020-07-06 10:16:03
【问题描述】:
我是在 Android 中实现自定义视图的新手。我已经实现了一个自定义视图(一个简单的矩形)。代码如下:
class CustomView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
// Paint styles used for rendering are initialized here. This
// is a performance optimization, since onDraw() is called
// for every screen refresh.
style = Paint.Style.FILL
textAlign = Paint.Align.CENTER
textSize = 55.0f
typeface = Typeface.create("", Typeface.BOLD)
color = Color.GREEN
}
private val rectangle = RectF(100f, 100f, 500f, 120f)
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas?.drawRect(rectangle, paint)
}
}
由于我的布局文件,应该放在屏幕中间:
<layout 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">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomViewFragment">
<com.example.learningcustomviewimplementation.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
但它位于左上角附近。从我在输出中看到的,没有使用约束。我需要更改什么,以便根据我在布局文件中使用的约束放置自定义视图?
【问题讨论】:
标签: android android-custom-view android-constraintlayout