I have an abstract BaseActivity
class with this layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize" />
<ViewStub
android:id="@+id/activity_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
All activities in the app extends BaseActivity and overrides a method called getLayoutResID
to provide its layout resource id which is inflated in the ViewStub
. I do this to avoid having the Toolbar in each layout. The code in the base class that is used to inflate the layout is this:
private void setupLayout() {
setContentView(R.layout.activity_base);
ViewStub viewStub = (ViewStub) findViewById(R.id.activity_layout);
viewStub.setLayoutResource(getLayoutResID());
viewStub.inflate();
}
One of my activities use the new Data Binding system, below its layout:
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.myapp.User" />
</data>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.name}" />
</layout>
Although the data binding works perfectly the problem is that the ToolBar is not visible. Any idea why the data binding engine removes/hides the toolbar in this activity?
ViewStubs requires special attention as they replace themselves when being inflated, rather than populating themselves. Read more on data-binding/guide#viewstubs
Another solution (to avoid ViewStub
altogether) is to let your ConcreteActivities
include a toolbar layout in their layout - instead of inflating a stub containing the toolbar. You'll also have less headache if you ever want to use custom a toolbar for an activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With