这些是您可以选择的选项。在项目中需要时,请使用其中之一。
最佳方式
做这件事的最佳方式是您在问题中已经提到的,添加一个BaseActivity
并将所有活动从它扩展。根据CoordinatorLayout
的官方文档,
CoordinatorLayout
主要用于以下两种情况:
- 作为顶级应用程序装饰或chrome布局
- 作为具有与一个或多个子视图的特定交互的容器
因此,CoordinatorLayout
主要是为此目的创建的(虽然还有其他原因)。如文档中所述,性能问题最少。
使用FrameLayout
就像Rainmaker已经回答的那样,您可以在布局文件夹中使用一个带有对CoordinatorLayout
布局的引用的活动,其中子项将是一个帧布局。
<?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)