这些是您拥有的选项。在项目中根据需要使用其中之一。
最好的方法
这样做的最佳方法是您在问题中已经说过,添加BaseActivity 并从中扩展您的所有活动。根据CoordinatorLayout的official documentation,
CoordinatorLayout 适用于两个主要用例:
- 作为顶级应用程序装饰或 chrome 布局
- 作为与一个或多个子视图进行特定交互的容器
所以CoordinatorLayout 的创建主要是因为这个原因(虽然也有other 的原因)。文档中提到的性能问题最少。
通过使用 FrameLayout
正如 Rainmaker 已经回答的那样,您可以在您的布局文件夹中使用引用 CoordinatorLayout 布局的 Activity,其中子级将成为框架布局。
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
android:id="@+id/activity_root"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
那么您将只使用一个带有setContentView(R.layout.root_coordinate_layout) 的活动。然后您将所有其他活动转换为片段并添加它们:
MyFragment myf = new MyFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction()
.add(R.id.your_layout, myf)
.commit();
程序化方式
这是做同样事情的另一种方式。但这有点复杂,需要做很多工作。
在您的所有活动中,请使用以下代码,而不是 setContentView(R.id.your_layout):
LayoutInflater inflater = LayoutInflater.from(this);
ConstraintLayout yourLayout = (ConstraintLayout) inflater.inflate(R.layout.your_layout, null, false);
CoordinatorLayout layout = new CoordinatorLayout(this);
// Set its property as you wish ...
layout.addView(mainScreen);
setContentView(layout);