? ? ? ? DrawerLayout是谷歌官方提供的,用于實(shí)現(xiàn)側(cè)滑菜單的一種抽屜式布局。
? ? ? ? 本文主要介紹DrawerLayout的簡(jiǎn)單使用。
? ? ? ? 詳細(xì)代碼:github.com/Baolvlv/LearnAndroid/tree/master/DrawerLayoutUsing
1.基本介紹
DrawerLayout,谷歌官方提供,實(shí)現(xiàn)側(cè)滑菜單,抽屜布局
2.創(chuàng)建抽屜布局
將根布局改為DrawerLayout,設(shè)置命名空間,id與寬高
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_height="match_parent"
android:layout_width=“match_parent">
設(shè)置抽屜隱藏時(shí)的主內(nèi)容布局,F(xiàn)rameLayout(運(yùn)行時(shí)由fragment填充)
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
設(shè)置左側(cè)抽屜式導(dǎo)航欄,ListView
設(shè)置id與寬高
android:id="@+id/left_drawer"
android:layout_width="240dp"
android:layout_height=“match_parent"
設(shè)置layout_gravity為start,即從左向右滑出,如果為end,即為從右向左滑出
android:layout_gravity="start"
設(shè)置背景為米白色:
android:background=“#ffffcc"
設(shè)置為單選
android:choiceMode=“singleChoice"
通過(guò)設(shè)置分割線顏色透明,寬度為0,使分割線不可見(jiàn)
android:divider="@android:color/transparent"
android:dividerHeight=“0dp">
注意事項(xiàng):
1.主內(nèi)容視圖是DrawerLayout的第一個(gè)子視圖
2.主內(nèi)容視圖的寬度和高度匹配父視圖
3.設(shè)置layout_gravity屬性為start,不推薦使用left
4.抽屜視圖寬度以dp為單位,不超過(guò)320dp
2.初始化抽屜式導(dǎo)航列表
初始化DrawerLayout和ListView,通過(guò)ArrayList儲(chǔ)存list中的條目,通過(guò)Adapter傳給ListView
mDrawerLayout= (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawList= (ListView) findViewById(R.id.left_drawer);
menuLists=newArrayList<>();
for(inti =0;i<5;i++){
menuLists.add("baolvlv"+i);
}
adapter=newArrayAdapter(this,
android.R.layout.simple_list_item_1,menuLists);
mDrawList.setAdapter(adapter);
新建contentFragment,繼承自fragment,作為填充frameLayout的fragment,同時(shí)創(chuàng)建布局資源文件,重寫(xiě)onCreateView方法
publicViewonCreateView(LayoutInflater inflater,@NullableViewGroup container,@NullableBundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content,container,false);
textView= (TextView) view.findViewById(R.id.text);
//獲得參數(shù),設(shè)置為textView的text的值
String text = getArguments().getString("text");
textView.setText(text);
returnview;
}
為側(cè)邊欄抽屜設(shè)置事件監(jiān)聽(tīng)器,主Activity實(shí)現(xiàn)onItemClickListener
mDrawList.setOnItemClickListener(this);
重寫(xiě)onItemClick方法,執(zhí)行點(diǎn)選后的操作
@Override
public voidonItemClick(AdapterView parent,View view, intposition, longid) {
//動(dòng)態(tài)插入一個(gè)fragment到FrameLayout當(dāng)中
Fragment contentFragment =newContentFragment();
//將點(diǎn)選的item作為參數(shù),通過(guò)Bundle傳遞給fragment
Bundle args =newBundle();
args.putString("text",menuLists.get(position));
contentFragment.setArguments(args);
//替換當(dāng)前fragment為新的fragment
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,contentFragment).commit();
//點(diǎn)選之后關(guān)閉左側(cè)的抽屜
mDrawerLayout.closeDrawer(mDrawList);
}