項目要實現類似於網易新聞客戶端的側滑拉出菜單的功能,搜了好些資料,有下面的三種方法:
1)自定義viewgroup
2)導入開源項目slidingmenu_library
3)採用V4包的組件DrawerLayout
第三種方法是最方便快捷的了,雖然第三種方法不能很好地支持低版本安卓手機,但是因爲我們也沒有這種需求,所以最後我還是決定採用DrawerLayout。不過第一種方法是最好的(雖然從開發效率上來說不是),有空自己還得要學一下自己造輪子。
DrawerLayout的xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="open" />
</FrameLayout>
<LinearLayout
android:id="@+id/left_layout"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#FFB5C5"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:textSize="20sp" >
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:textSize="20sp" >
</TextView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
其中包裹了2個或者以上的view,需要注意的是第一個view是主頁面的view,後面的纔是側滑出頁面的view。主頁面view的寬高要寫成
android:layout_width="match_parent"
android:layout_height="match_parent"
因爲在沒有側滑的時候是要包裹父view窗體的。
而在側滑出的頁面的view要設置layout_gravity的值指明是向左滑出還是向右滑出。
下面的Activity,比較簡單:
package com.example.drawerlayout;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
Button button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 按鈕按下,將抽屜打開
mDrawerLayout.openDrawer(Gravity.LEFT);
}
});
}
}
直接調用openDrawer就可以拉開側滑頁面了。需要注意的是後面也要寫明側滑方向(LEFT),並且與前面xml標明的方向要一致,不然可能會出錯。
DrawerLayout還有很多很好用的API,我還在研究中所以就不貼出來了。