我可以将视图的内容设置为 XML 文件吗?
Can I set the content of a View to an XML file?
我想制作一个自定义视图,我已经有一个 XML 布局文件,但我似乎找不到这样做的方法。
setContentView()
不存在于 类 中,不是从 Activity 派生的,而且我不知道如何渲染用 LayoutInflater
膨胀的视图。
我的观点基于 RelativeLayout
,如果有帮助的话。
您可以使用 the static View.inflate()
method 并将您的 RelativeLayout
作为第三个参数传递。
val relative = /* your RelativeLayout here */
View.inflate(context, R.layout.your_layout_file, relative)
与 setContentView()
不同,这不会删除 RelativeLayout 的任何现有子项。所以你可能想先调用它:
relative.removeAllViews()
您可以创建自定义 View
class 扩展 RelativeLayout
:
class CustomRelativeLayout(
context: Context,
attrs: AttributeSet
) : RelativeLayout(context, attrs)
{
init {
inflate(context, R.layout.your_layout, this)
}
}
然后将其用于:
<CustomRelativeLayout></CustomRelativeLayout>
在您的 XML 个文件中。
我想制作一个自定义视图,我已经有一个 XML 布局文件,但我似乎找不到这样做的方法。
setContentView()
不存在于 类 中,不是从 Activity 派生的,而且我不知道如何渲染用 LayoutInflater
膨胀的视图。
我的观点基于 RelativeLayout
,如果有帮助的话。
您可以使用 the static View.inflate()
method 并将您的 RelativeLayout
作为第三个参数传递。
val relative = /* your RelativeLayout here */
View.inflate(context, R.layout.your_layout_file, relative)
与 setContentView()
不同,这不会删除 RelativeLayout 的任何现有子项。所以你可能想先调用它:
relative.removeAllViews()
您可以创建自定义 View
class 扩展 RelativeLayout
:
class CustomRelativeLayout(
context: Context,
attrs: AttributeSet
) : RelativeLayout(context, attrs)
{
init {
inflate(context, R.layout.your_layout, this)
}
}
然后将其用于:
<CustomRelativeLayout></CustomRelativeLayout>
在您的 XML 个文件中。