This can be achieved by using a custom layout for your navigation drawer alongside a custom implementation of DrawerLayout.DrawerListener
. Below is a very simple example that can be easily adapted to the code generated by Android Studio's "New Project -> Navigation Drawer Activity".
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="@+id/nav_view"
android:layout_width="@dimen/navdrawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#ccc">
<ImageView
android:id="@+id/image"
android:layout_width="256dp"
android:layout_height="256dp"
android:layout_gravity="center"
android:src="@drawable/mydrawable"/>
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.image);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerLayout.DrawerListener listener = new MyActionBarDrawerListener();
drawer.addDrawerListener(listener);
}
private class MyActionBarDrawerListener extends DrawerLayout.SimpleDrawerListener {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
int navdrawerWidth = getResources().getDimensionPixelSize(R.dimen.navdrawer_width);
float closedAmount = (1 - slideOffset);
int marginStart = 2 * (int) (navdrawerWidth * closedAmount);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) iv.getLayoutParams();
MarginLayoutParamsCompat.setMarginStart(params, marginStart);
iv.setLayoutParams(params);
}
}
}
The core of the solution is that you provide a background image but update its marginStart
attribute as the drawer slides. You can fiddle with the exact numbers to get the amount of sliding that you like.
Note that I've omitted a lot of code in order to improve readability. In practice you would probably have MyActionBarDrawerListener
extend from ActionBarDrawerToggle
so that you'd get the navigation icon etc.