Reputation: 1
I have a sliding drawer in my application.
It open when I click on android:handle
, which I have given to an image view.
I want to close the drawer when back button is pressed.
Code:
SlidingDrawer slider;
@Override
public void onBackPressed() {
slider.close ();
}
super.onBackPressed();
Main. Xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="right"
android:orientation="vertical" >
<SlidingDrawer
android:id="@+id/slider"
android:layout_width="150dp"
android:layout_marginRight="0dp"
android:layout_height="match_parent"
android:handle="@+id/handle"
android:content="@+id/content"
android:orientation="horizontal"
>
<ImageView
android:id="@+id/handle"
android:background="@drawable/up"
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
/>
<GridView
android:id="@+id/content"
android:background="@color/black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</SlidingDrawer>
</LinearLayout>
</RelativeLayout>
Activity file
@Override
public void onCreate(Bundle savedInstanceState)
{
SlidingDrawer slide = (SlidingDrawer)this.findViewById(R.id.slider);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override public void onBackPressed() {
if(slide.isOpened()){
slide.close ();
}
else{
super.onBackPressed();
}
}
}
Upvotes: 0
Views: 3432
Reputation: 11608
You only need to close it if it's actually opened:
SlidingDrawer slider;
@Override
public void onBackPressed() {
if (slider.isOpened()) {
slider.close ();
} else {
super.onBackPressed();
}
}
EDIT
your slider
field is out of scope. You need to declare it as a class field in order it can be accessed by all non-static methods. Also consult this document.
Upvotes: 3
Reputation: 1442
You don't call the super method inside the in on back pressed method you just give this only...
@Override
public void onBackPressed() {
slider.close ();
}
Don't call Super method inside the back pressed
Upvotes: 0