以编程方式包含布局
Include layout programmatically
我的 android 应用程序中有 3 个 windows。所以,我认为会有 3 个活动。还有一个导航抽屉。导航抽屉必须在每个 Activity 上可用。我在 Android Studio 中使用了模式导航抽屉 Activity。有3个xml-layouts:
1). activity_main.xml – 有一个 NavigationView ,包括 app_bar_main.xml
2). app_bar_main.xml – 包括 content_main.xml
3). content_main.xml – 这里会有一些内容(文字、图片等)
每个Activity当然都有不同的内容。所以每个 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 的文本。所以一个文本覆盖另一个。
我做错了什么?
尝试像这样设置您的子视图 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);
你可以看看Fragments。它将帮助您在需要时以相同的 activity 打开各种布局。此外,您也可以重复使用导航抽屉。
我的 android 应用程序中有 3 个 windows。所以,我认为会有 3 个活动。还有一个导航抽屉。导航抽屉必须在每个 Activity 上可用。我在 Android Studio 中使用了模式导航抽屉 Activity。有3个xml-layouts:
1). activity_main.xml – 有一个 NavigationView ,包括 app_bar_main.xml
2). app_bar_main.xml – 包括 content_main.xml
3). content_main.xml – 这里会有一些内容(文字、图片等)
每个Activity当然都有不同的内容。所以每个 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 的文本。所以一个文本覆盖另一个。
我做错了什么?
尝试像这样设置您的子视图 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);
你可以看看Fragments。它将帮助您在需要时以相同的 activity 打开各种布局。此外,您也可以重复使用导航抽屉。