重新核准布局butterknife
我有一个包含该结构的BaseActivity:重新核准布局butterknife
<!-- activity_base -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<include
layout="@layout/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<include
layout="@layout/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/tool_bar"
android:layout_above="@id/bottom_navigation" />
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="@menu/bottom_navigation_menu" />
</RelativeLayout>
在我BaseActivity
我控制BottomNavigationView
。我创建了几个活动,我想利用包含内容并只加载该活动的内容。 今天该项目正在使用butterknife
Java。而且该项目越来越庞大,因为它正在复制每个子活动的顶层结构BaseActivity
。我想重构(以最好和最快的方式)该项目,以便只有一个 activity_base.xml
和其他活动仅控制其内容(content.xml
)。 我看到一些使用ViewStub
和另一个描述<merge>
但我不明白如何在项目中轻松应用概念,因为许多使用活动和片段,我的项目只与活动。
我不是这个解决方案完全满意,但我结束了类似的东西在一个类似的案子:
base_activity.xml
<...>
..... Whatever you want at the top
<.../>
<!-- Container where your child Activity layout will be inflated -->
<FrameLayout
layout="@+id/child_activity_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<...>
..... Whatever you want at the bottom
<.../>
BaseActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
ViewGroup parent = findViewById(R.id.child_activity_container);
View childView = inflateChildLayout(LayoutInflater.from(this), parent);
// The child Activity can have no layout (for some reason)
if (childView != null) {
parent.addView(childView);
}
ButterKnife.bind(BaseActivity.this);
// ... the rest of your onCreate
}
@Nullable
protected abstract View inflateChildLayout(LayoutInflater inflater, ViewGroup parent);
ChildActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(...); // Already managed by the base Activity so we don't need it
}
@Override
protected View inflateChildLayout(LayoutInflater inflater, ViewGroup parent) {
return inflater.inflate(R.layout.activity_child, parent, false);
}
的想法是BaseActivity
管理子布局的通货膨胀其自身的内部布局和管理呼叫ButterKnife。由于父母和孩子实际上是相同的实例(就像ChildActivity扩展了BaseActivity一样)ButterKnife父母和孩子的Views。这就是为什么在拨打inflateChildLayout
我不知道ViewSub,所以你可以用它来改善上面的代码。 – Eselfar
之后调用它的原因是否可以为所有活动使用完全相同的layout.xml? –