官網:https://developer.android.com/training/implementing-navigation/nav-drawer.html
貼上主要的邏輯和佈局文件:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- content --> <FrameLayout android:id="@+id/drawer_container" android:layout_width="match_parent" android:layout_height="match_parent"/> <!-- Drawer--> <ListView android:id="@+id/drawer_menu" android:layout_width="240dp" android:layout_height="match_parent" android:background="#FFF0F0F0" android:layout_gravity="start"/> <!-- android:choiceMode 选中状态 跟onItemClick没有冲突 none 值为0,表示无选择模式; singleChoice 值为1,表示最多可以有一项被选中; multipleChoice 值为2,表示可以多项被选中。 android:layout_gravity left或right left或start right或end 表示在抽屉里的效果是从左到右还是从右到左出现 --> </android.support.v4.widget.DrawerLayout>
這裡需要注意一下介面一定要定義在drawer的前面,另外,Android:layout_gravity="start"(從左往右)或android:layout_gravity="end"(從右往左),這個屬性是必須要定義的,不然出現下面的異常:
MainActivity.java
package com.jackie.drawerlayoutdemo; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private String mTitle; private DrawerLayout mDrawerLayout; private ListView mDrawerMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); //默认打开抽屉 mDrawerLayout.openDrawer(mDrawerMenu); } private void initView() { mTitle = getResources().getString(R.string.app_name); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerMenu = (ListView) findViewById(R.id.drawer_menu); } private void initData() { //数组定义在xml 文件中 String[] items = getResources().getStringArray(R.array.left_drawer_items); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1); adapter.addAll(items); mDrawerMenu.setAdapter(adapter); mDrawerMenu.setSelection(0); //设置点击item事件 mDrawerMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mTitle = ((TextView) view).getText().toString(); switchFragment(); mDrawerLayout.closeDrawer(mDrawerMenu); mDrawerMenu.setSelection(position); } }); } private void switchFragment() { getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, new ItemFragment(mTitle)).commit(); getSupportActionBar().setTitle(mTitle); } }
效果圖如下:
以上所述是小編給給大家介紹的Android DrawerLayout
以上所述是小編給大家介紹的Android DrawerLayout。有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對PHP中文網的支持!
更多Android DrawerLayout實現抽屜效果實例代碼相關文章請關注PHP中文網!