My MainActivity
implements NavigationView
, so mostly the whole contents of the screen are inside FrameLayout
. In one of the Fragments
, I have a ViewPager
, I want that when that Fragment
is launched, the elevation
from Toolbar
gets removed, and otherwise gets re-added.
My target API is 29, and I don't care for the support of older versions.
activity_main.xml
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<include
layout="@layout/toolbar"/>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="@+id/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<include layout="@layout/navigation_drawer"/>
</androidx.drawerlayout.widget.DrawerLayout>
fragment_view_pager.xml
<androidx.viewpager.widget.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabs_vp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabs_tl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:background="?android:attr/colorPrimary">
</com.google.android.material.tabs.TabLayout>
</androidx.viewpager.widget.ViewPager>
I think this is the simplest answer, in the ViewPager
fragment:
private var myElevation: Float? = null
override fun onCreateView(/* params */) {
// other code
myElevation = activity!!.app_bar_id.elevation
activity!!.app_bar_id.elevation = 0f
}
override fun onDestroyView() {
super.onDestroyView()
activity!!.app_bar_id.elevation = myElevation!!
}
In this way, the elevation is 0
only when the ViewPager
Fragment is active.