Android布局模板

时间:2011-12-08 10:33:24

标签: android android-layout templates android-xml

我正在寻找一种在android中进行布局模板化的简单方法。 我已经检查了包含和合并技术但没有成功。 (我认为可以创建自定义布局并通过代码定义此行为,但我想知道是否可以通过xml完成​​)

我想定义这样的内容:

 [globalLayout]
 <linearLayout params=xxx>
    <linearLayout params=yyy>
        <?yied ?>
    </linearLayout>
 </linearLayout>


 [customView1]
 <Linearlayout>
   <ImageView />
   <Button/>
 </LinearLayout>


 [customView2]
 <Linearlayout>
   <Button/>
   <Button/>
   <Button/>
 </LinearLayout>

(这些3 xml应该可以重复使用)

 [HomeLayout]
 <?include globalLayout >
    <?include customView1 />
 </include>


 [ParamsLayout]
 <?include globalLayout >
    <?include customView2 />
 </include>

问题是我希望有一个可重复使用的布局,如果执行一个小的更改,它将影响所有相关的视图。有些想法与其他语言的“部分观点或模板”有关。

有人可以帮助我吗?

4 个答案:

答案 0 :(得分:2)

我认为对于xml定义来说这是不可能的,因为系统无法确定在复杂的方案布局中添加视图的位置。

无论如何,如果您定义自己的布局,您可以轻松地执行此操作。查看这篇文章了解更多详情 Custom Layout in android

答案 1 :(得分:0)

我以前通过使用视图存根做了类似的事情。 您可以在该视图中为您喜欢的任何视图充气。

<GlobalLayout>
 <ViewStub>
<GlobalLayout>

答案 2 :(得分:0)

使用LayoutInflater执行以下操作:

在活动的onCreate上:

    super.onCreate(savedInstanceState);
    setContentView(new TemplateInflater(this).apply(R.layout.products)
              .onViewGroup(R.id.replace_here).ofTemplate(R.layout.template));

实施代码段:

public View ofTemplate(int templateId) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View root = inflater.inflate(templateId, null);

    View content = inflater.inflate(contentId, null);
    ((ViewGroup)root.findViewById(viewGroupId)).addView(content);

    return root;
}

工作代码的一个例子在我的git中:https://github.com/erichegt/AndroidTemplating

我认为此代码可以解决您的问题,但您应该使用Fragments。您可以将一个与模板关联的活动和一个片段对其进行充气。

答案 3 :(得分:0)

ViewStub非常简单,可以满足基本的布局模板需求。

它可以作为其他布局的占位符,您可以在运行时指定和扩展,然后:

  

使用ViewStub的布局参数将膨胀的视图添加到ViewStub的父级。

以下是我的一个项目的示例。在我的布局模板中,我有:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout ... >

    ...

    <ViewStub
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/button_1_stub"
        app:layout_constraintDimensionRatio="H,1:1"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/split_guideline"
        app:layout_constraintLeft_toRightOf="@+id/primary_left_guideline"
        app:layout_constraintRight_toLeftOf="@+id/primary_right_guideline">
    </ViewStub>

    ....

</android.support.constraint.ConstraintLayout>

...然后,当我给它充气时,我正在设置我需要的实际按钮布局并充气存根:

    View contentView = inflater.inflate(R.layout.activity_main_template, null);
    ViewStub button1Stub = contentView.findViewById(R.id.button_1_stub);
    button1Stub.setLayoutResource(R.layout.work_button);
    button1Stub.inflate();

...从R.layout.work_button而不是存根插入布局,强加了我在R.id.button_1_stub上定义的布局约束。