Учимся создавать слайдинг меню
MainActivity
package amurdroid.myappvbok;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick1(View view) {
setContentView(R.layout.activity_second);
}
}
MainActivity
package amurdroid.myappvbok;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClick1(View view) {
setContentView(R.layout.activity_second);
}
}
1. Горизонтальное выдвижение.
Activity_main
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/ic_launcher" />
<SlidingDrawer
android:id="@+id/drawer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:content="@+id/content"
android:handle="@+id/handle"
android:orientation="horizontal" >
<ImageView
android:id="@+id/handle"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="@drawable/ic_launcher" />
<LinearLayout
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#55000000"
android:orientation="vertical"
android:padding="10dp" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onClick1"
android:text=" - Button - " />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" - Button - " />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" - Button - " />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" - Button - " />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" - Button - " />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" - Button - " />
</LinearLayout>
</SlidingDrawer>
</FrameLayout>
Наиболее важные атрибуты:
- handle - определяет идентификатор (id) управляющего элемента
- content - определяет идентификатор (id) содержимого
- orientation - определяет ориентацию виджета, по умолчанию vertical
Методы
- animateClose() - закрыть виджет с анимацией
- animateOpen() - открыть виджет с анимацией
- animateToggle() - переключить состояние открыт/закрыт
- close() - закрыть виджет без анимации
- getContent() - получить окно содержимого
- getHandle() - получить окно управляющего элемента
- isMoving() - проверяет, находится ли виджет в движении
- isOpened() - проверяет, открыт ли виджет
- lock() - заблокировать виджет, события касания будут игнорироваться
- onInterceptTouchEvent(MotionEvent event) - метод для перехвата всех события прикосновения
- onTouchEvent(MotionEvent event) - метод для того, что делать при касании на экран
- open() - открыть виджет
- setOnDrawerCloseListener(SlidingDrawer.OnDrawerCloseListener onDrawerCloseListener) - обработчик закрытия виджета
- setOnDrawerOpenListener(SlidingDrawer.OnDrawerOpenListener onDrawerOpenListener) - обработчик открытия виджета
- setOnDrawerScrollListener(SlidingDrawer.OnDrawerScrollListener onDrawerScrollListener) - обработчик прокрутки виджета
- toggle() - переключить состояние открыт/закрыт без анимации
- unlock() - разблокировать виджет
2. Вертикальное
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="390dip"
android:layout_gravity="bottom"
android:background="#808080" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Пример: \nИспользуем SlidingDrawer" />
<SlidingDrawer
android:id="@+id/drawer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:content="@+id/content"
android:handle="@+id/handle"
android:orientation="vertical" >
<ImageView
android:id="@+id/handle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#404040"
android:src="@drawable/ic_launcher" />
<LinearLayout
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="200dip"
android:background="#606060"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" - Button - " />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" - Button - " />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" - Button - " />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Содержимое" />
</LinearLayout>
</SlidingDrawer>
</FrameLayout>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Неперемещаемая кнопка" />
</LinearLayout>
Немного кода
Мы рассмотрели примеры без написания кода. Вот простой пример с динамическим изменением изображения для "ручки ящика". Первоначально на экране отображается стрелка вверх, когда мы дотянем эту ручку до конца, то сменим изображение на стрелку вниз. Разметку можно оставить от последнего примера. Предварительно вам надо подготовить изображения со стрелками и скопировать их в папку drawable.
package ru.alexanderklimov.slidingdrawer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.SlidingDrawer.OnDrawerScrollListener;
public class SlidingDrawerDemoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView ibHandle = (ImageView) findViewById(R.id.handle);
SlidingDrawer slidingdrawer = (SlidingDrawer) findViewById(R.id.drawer);
slidingdrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
public void onDrawerOpened() {
ibHandle.setImageResource(R.drawable.icon_down);
}
});
slidingdrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
public void onDrawerClosed() {
ibHandle.setImageResource(R.drawable.icon_up);
}
});
// slidingdrawer.setOnDrawerScrollListener(new OnDrawerScrollListener() {
//
// public void onScrollEnded() {
// // TODO Auto-generated method stub
//
// }
//
// public void onScrollStarted() {
// // TODO Auto-generated method stub
// }
// });
}
}
В примере закоментированы строчки метода, который выполняется при скроле. Нас сейчас интересуют только момент открытия и закрытия.