Android的编程包括布局(即没有XML) [英] Android programmatically include layout (i.e. without XML)

查看:200
本文介绍了Android的编程包括布局(即没有XML)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我创建了一个活动子类,称为CustomTitlebarActivity。从本质上讲,在我的应用程序的每个主要活动将有一个自定义标题栏具有许多共同的特征,如Home键,一个标题,一个搜索按钮,等等。在我目前的执行情况,我仍然明确地使用包括在布局XML语句每个CustomTitlebarActivity:

So I've created an Activity subclass called CustomTitlebarActivity. Essentially, each main activity in my app will have a custom titlebar with many common features such as a Home button, a title, a search button, etc. In my current implementation, I am still explicitly using an include statement in the layout XML for each CustomTitlebarActivity:

<include layout="@layout/titlebar" />

很自然,我应该能够在CustomTitlebarActivity做到这一点。我有两个问题:什么code可以代替这个包括标签,并在那里我应该把code? (我的第一反应是把它放在CustomTitlebarActivity的的setContentView方法。)

It seems natural that I should be able to do this within CustomTitlebarActivity. I have two questions: What code can replace this include tag, and where should I put the code? (My first instinct would be to put it in CustomTitlebarActivity's setContentView method.)

在一个相关的说明,我将AP preciate洞察更好的方法来重用的Andr​​oid UI code(即使本身的标题栏需要稍微有所不同活动之间。)

On a related note, I would appreciate insight into better ways to reuse android UI code (even if, per se, the titlebars need to vary slightly between activities.)

推荐答案

就个人而言,我可能会写我的活动子总是的setContentView 来包含一个垂直 FILL_PARENT 的LinearLayout 只包含我的标题栏布局文件:

Personally, I'd probably write my Activity subclass to always setContentView to a layout file containing a vertical fill_parent LinearLayout containing only my title bar:

<LinearLayout android:id="@+id/custom_titlebar_container"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   <!--titlebar here-->
</LinearLayout>

随后,我会定义一个抽象 getContentAreaLayoutId()方法 CustomTitlebarActivity 返回内容的布局ID下面的标题栏的每个子类;基的onCreate() CustomTitlebarActivity 会就可以致电

Then I'd define an abstract getContentAreaLayoutId() method in CustomTitlebarActivity that returns the layout ID of the content below the titlebar for each subclass; the base onCreate() of CustomTitlebarActivity would then just call

setContentView(R.layout.custom_titlebar_activity_frame_from_above);
View.inflate(this, getContentAreaLayoutId(), findViewById(R.id.custom_titlebar_container));

另外,你可以有你的获取内容区域返回抽象方法查看,而不是 INT ,给你更多的灵活性,以动态地构造你的看法(但强迫你自己抬高他们在简单的只转储这个XML布局在这里的情况下)。

Alternatively, you could have your abstract method for getting the content area return a View rather than an int, giving you more flexibility to construct your views dynamically (but forcing you to inflate them yourself in the simple "just dump this XML layout here" case).

这篇关于Android的编程包括布局(即没有XML)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆