简体   繁体   English

如何在android中创建自定义布局?

[英]How can I create custom layout in android?

I have container repeated at more than view.我在不止视图中重复了容器。
How can I create this container just one time and implement its class using builder design pattern.我怎样才能一次创建这个容器并使用构建器设计模式实现它的类。

Example: I have TextView its color and text changed according to the fragment.示例:我根据片段更改了 TextView 的颜色和文本。

Hi your common layout for your textView name it as layout_text_view.xml嗨,您的 textView 的通用布局将其命名为 layout_text_view.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
    <variable
        name="dark"
        type="Boolean" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/txtTitle"
        android:text="Some Random Text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:drawablePadding="@dimen/padding_medium"
        android:textColor='@{dark?@color/white:@color/colorBlack}'
        android:textSize="@dimen/txt_xxxx_large"
        app:fontFamily="@font/sfprotext_bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

You can use this layout in your fragments with include tag like this你可以在你的片段中使用这个布局,像这样包含标签

<include
        android:id="@+id/toolbar"
        layout="@layout/layout_toolbar"
        app:dark='@{true}'
        />

You can use many values in data tag which will change your common ayout_text_view.xml file.您可以在数据标记中使用许多值,这将更改您的常用ayout_text_view.xml 文件。

Note- I have assumed you may be using data binding in your project if not then paste注意-我假设您可能在项目中使用数据绑定,如果没有,则粘贴

dataBinding {
    enabled true
}

in your build.gradel(App level) .在您的 build.gradel(App level) 中。 In android tag在安卓标签中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM