android - 添加自定义 View 组件时应用程序停止

标签 android android-studio kotlin

我尝试使用 Kotlin 在 Android Studio 中创建时钟。 我创建了一个带有时钟的 View ,您可以看到代码。

class ClockView(c: Context, attrs: AttributeSet?, defStyleAttr: Int) : View(c, attrs, defStyleAttr) {
    private val paint = Paint()

    init {
        paint.color = Color.BLACK
        paint.style = Paint.Style.FILL
        paint.textSize = 60F
        paint.isAntiAlias = true
    }

    override fun onDraw(canvas: Canvas?) {
        val calendar = Calendar.getInstance()
        val hour: String = calendar.get(Calendar.HOUR_OF_DAY).toString()
        val minute: String = calendar.get(Calendar.MINUTE).toString()
        val second: String = calendar.get(Calendar.SECOND).toString()

        canvas?.drawColor(Color.WHITE)
        canvas?.drawText(hour, width / 2F - 200F, height / 2F, paint)
        canvas?.drawText(minute, width / 2F - 100F, height / 2F, paint)
        canvas?.drawText(second, width / 2F, height / 2F, paint)

        postInvalidateDelayed(500)
        invalidate()

        super.onDraw(canvas)
    }
}

我将其实现到我的 MainActivity 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <com.example.adnroid_clock.ClockView
       android:id="@+id/ClockView"
       android:layout_width="304dp"
       android:layout_height="243dp"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintHorizontal_bias="0.495"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent"
       app:layout_constraintVertical_bias="0.157" />

</androidx.constraintlayout.widget.ConstraintLayout>

我启动应用程序时遇到了该错误。 Run log

最佳答案

堆栈跟踪显示您使用 androidx.constraintlayout.Dwidget.ConstraintLayout (注意 . 之间的 D widget)在某些布局文件中。考虑到堆栈跟踪的设置方式,这可能是您的 Activity 的布局文件。

无论如何,找到带有这个额外 D 的布局,然后删除 D

关于android - 添加自定义 View 组件时应用程序停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66844867/

相关文章:

android - 为什么 Gradle 无法解析 Kotlin Gradle 插件

android - 启动Android Studio时出现的一长串错误

android - 使用 repeatOnLifeCycle 从 UI 中的 Flow 收集

android - Recycler View 双向滚动

android - 使用可跨越字符串更改阿拉伯语变音符号颜色在某些手机上不起作用

java - 由 : java. lang.IllegalArgumentException : Binary XML file line #9: Must specify unique android:id, android :tag, 引起,或者有一个 id 为

android - 如何使用 Koin 在 BaseFragment 中注入(inject) viewModel

android - adb 拉取多个文件

android - 无法在 android studio 3.6 中进行 git pull

android - Log.e 与 Kotlin