首页 > 解决方案 > 如何使用 XML 文档创建这样的 XML 文件?

问题描述

基本上我想通过像这样创建XML文件在android中添加我的自定义属性和默认文本视图我怎样才能像这样创建我自己的XML文档?喜欢

<TextView
android:id="@+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"`enter code here`
android:text="TextView"
customfontdemo:fontName="Anything"
tools:layout_editor_absoluteX="163dp"
tools:layout_editor_absoluteY="166dp" />

所以这是我的自定义属性#fontName我想在默认 UI 组件中添加我的自定义属性我该怎么做?并在 .kt 文件中读取

标签: androidandroid-studioandroid-layoutkotlin

解决方案


如果我理解正确,您希望能够在现有视图上使用自定义属性。

为此,您将需要“劫持”通货膨胀过程。实现这一目标的方法是实现自定义 LayoutInflator.factory 或 factory2 如果您的目标是 api 11+(旁注:android 团队需要学习如何命名事物)

工厂是一个包含函数的接口

View onCreateView(View parent, String name, Context context, AttributeSet attrs)

这是从源代码中获取的完整界面

 public interface Factory2 extends Factory {
    /**
     * Version of {@link #onCreateView(String, Context, AttributeSet)}
     * that also supplies the parent that the view created view will be
     * placed in.
     *
     * @param parent The parent that the created view will be placed
     * in; <em>note that this may be null</em>.
     * @param name Tag name to be inflated.
     * @param context The context the view is being created in.
     * @param attrs Inflation attributes as specified in XML file.
     *
     * @return View Newly created view. Return null for the default
     *         behavior.
     */
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
}

查看本教程以帮助您实现工厂。实施工厂后,您可以更换

活动的

setContentView(View)

片段/简单膨胀类型

onCreateView()

推荐阅读