Android 以编程方式包含布局(即没有 XML)

2022-01-25 00:00:00 include android java

所以我创建了一个名为 CustomTitlebarActivity 的 Activity 子类.本质上,我的应用程序中的每个主要活动都有一个自定义标题栏,其中包含许多常见功能,例如主页按钮、标题、搜索按钮等.在我当前的实现中,我仍然在布局 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 中执行此操作似乎很自然.我有两个问题:什么代码可以替换这个包含标签,我应该把代码放在哪里?(我的第一反应是把它放在 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.)

在相关说明中,我希望能深入了解重用 android UI 代码的更好方法(即使标题栏本身需要在活动之间略有不同.)

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.)

推荐答案

就个人而言,我可能会将我的 Activity 子类编写为始终 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>

然后我会在 CustomTitlebarActivity 中定义一个抽象的 getContentAreaLayoutId() 方法,该方法返回每个标题栏下方内容的布局 ID子类;CustomTitlebarActivity 的基础 onCreate() 然后将调用

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));

或者,您可以让获取内容区域的抽象方法返回 View 而不是 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).

相关文章