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

Jon*_*lis 35 java android include

所以我创建了一个名为CustomTitlebarActivity的Activity子类.基本上,我的应用程序中的每个主要活动都将有一个自定义标题栏,其中包含许多常用功能,如主页按钮,标题,搜索按钮等.在我当前的实现中,我仍然在布局XML中明确使用include语句每个CustomTitlebarActivity:

<include layout="@layout/titlebar" />
Run Code Online (Sandbox Code Playgroud)

我应该能够在CustomTitlebarActivity中执行此操作,这似乎很自然.我有两个问题:什么代码可以替换此包含标记,我应该在哪里放置代码?(我的第一直觉是将它放在CustomTitlebarActivity的setContentView方法中.)

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

aco*_*tic 59

我也遇到了这个问题,现在我就解决了.我认为我的解决方案更容易:

  1. 创建一个inflater:

    LayoutInflater inflater = (LayoutInflater)      this.getSystemService(LAYOUT_INFLATER_SERVICE);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 给孩子布局充气:

    View childLayout = inflater.inflate(R.layout.child,
                (ViewGroup) findViewById(R.id.child_id));
    
    Run Code Online (Sandbox Code Playgroud)
  3. 将其添加到父级:

    parentLayout.addView(childLayout);
    
    Run Code Online (Sandbox Code Playgroud)

它完成了,享受它!

  • 我认为它应该是`findViewById(R.id.child_id));`不是`R.layout.child_id` (7认同)

Yon*_*lan 18

就个人而言,我可能Activity总是把我的子类写到setContentView一个包含一个fill_parent LinearLayout只包含我的标题栏的垂直的布局文件中:

<LinearLayout android:id="@+id/custom_titlebar_container"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   <!--titlebar here-->
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

然后我将定义一个抽象getContentAreaLayoutId()方法CustomTitlebarActivity,返回ID每个子类标题栏下面的内容布局; 底座onCreate()CustomTitlebarActivity,然后只需调用

setContentView(R.layout.custom_titlebar_activity_frame_from_above);
View.inflate(this, getContentAreaLayoutId(), findViewById(R.id.custom_titlebar_container));
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用抽象方法来获取内容区域View而不是一个内容区域int,从而使您可以更灵活地动态构建视图(但是在这里简单地转储此XML布局的情况下,强制您自己给它们充气).