【发布时间】:2023-02-17 15:35:07
【问题描述】:
我最近将 Android Studio 更新为 Android Studio Electric Eel | 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 问题?
【问题讨论】:
-
尝试重建项目并再次打开布局。
标签: android android-studio android-layout android-studio-electric-eel