以编程方式包含布局

时间:2015-11-25 10:18:55

标签: android android-layout include android-xml

我的Android应用程序中有3个窗口。所以,我认为会有3项活动。还有一个导航抽屉。导航抽屉必须在每个活动上都可用。我在Android Studio中使用了模式导航抽屉活动。有3个xml布局:

1)。 activity_main.xml - 有一个NavigationView,包含app_bar_main.xml

2)。 app_bar_main.xml - 包含content_main.xml

3)。 content_main.xml - 这里将是一些内容(文本,图片等)

每个活动当然都有不同的内容。所以每个Activity都有自己的content_main.xml。我需要以编程方式更改app_bar_main.xml中包含的此布局(不在activity_main.xml中)。我试过这个:

CoordinatorLayout mainLayout = (CoordinatorLayout) findViewById(R.id.app_bar_layout); LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mainLayout.addView(1, layoutInflater.inflate(R.layout.content_main, this, false));

但是最后一行加下划线并说'无法解决方法inflate()'。

我也试过这个:

CoordinatorLayout mainLayout = (CoordinatorLayout) findViewById(R.id.app_bar_layout); View child = getLayoutInflater().inflate(R.layout.content_main, null); mainLayout.addView(child);

但是这显示了工具栏标题上的content_main.xml文本。所以一个文字覆盖另一个文本。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

尝试设置您的子视图LayoutParams,如:

CoordinatorLayout mainLayout = (CoordinatorLayout) findViewById(R.id.app_bar_layout);
        View child = getLayoutInflater().inflate(R.layout.content_main, null);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(WEIGHT, HEIGHT);
        params.setMargins(MARGIN, MARGIN, MARGIN, MARGIN);
        child.setLayoutParams(params);
        mainLayout.addView(child);

答案 1 :(得分:0)

您可以查看Fragments。它可以帮助您在调用时在同一个活动中操作各种布局。此外,您也可以重复使用导航抽屉。

相关问题