Android Studio Eel xml预览未显示,自定义组件缺少类

zz2j4svz  于 2023-01-26  发布在  Android
关注(0)|答案(1)|浏览(165)

我最近将Android Studio更新为Android Studio电鳗|2022年1月1日。
对于XML布局,如果我们使用简单视图(如TextView/Button),则会在预览中显示。但如果我们使用CustomView,则不会在预览中显示。(预览为空)
同时显示错误:缺少类

我的简单测试应用程序,主活动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.webviewdeeplink.CustomTextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is Test Text"
        android:textSize="24sp"
        app:font="RobotoCondensed-LightItalic.ttf"
        app:layout_constraintBottom_toTopOf="@id/button"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <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_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

自定义组件类-

class CustomTextView : androidx.appcompat.widget.AppCompatTextView {

    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context!!,
        attrs,
        defStyle
    ) {
        init(attrs)
    }

    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {

        init(attrs)
    }

    constructor(context: Context?) : super(context!!) {

        init(null)
    }

    private fun init(attrs: AttributeSet?) {
        if (attrs != null) {
            val a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView)
            val fontName = a.getString(R.styleable.CustomTextView_font)
            try {
                if (fontName != null) {
                    val myTypeface = Typeface.createFromAsset(
                        context.assets,
                        "fonts/$fontName"
                    )
                    setTypeface(myTypeface)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            a.recycle()
        }
    }
}

如果有人遇到这个问题,请确认这个问题。或者这是已知的Android Studio问题?

w8biq8rn

w8biq8rn1#

试试这个代码...

constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
    context!!,
    attrs,
    0
) {
    init(attrs)
}

defStyle替换为0

相关问题