此爲第一個製做側滑菜單的實踐 。html
此部分僅僅爲部分實踐:java
僅缺menu的字符串佈局,以及須要修改的MainActivity.java文件,也是須要主要修改的地方。android
從使用MD設計-進行側滑菜單的製做(activity_main.xml部分)仍然可看。web
當中爲了向前兼容以及使用Material Design,參考了約10個連接。app
文件路徑、參考連接爲文章末尾,爲了更好的閱讀體驗,增長了文件源代碼展現(部分代碼有刪改)。ide
進行4.0系統的一些工做佈局
參考連接-向前兼容-1gradle
首先準備添加MD設計包,但考慮到Android Icecream(4.0)僅爲14,參考連接中得知Appcomat爲21,因此先作如下調整:ui
android { compileSdkVersion 21 defaultConfig { applicationId "product.felixxiong.com.MyPackgeName" minSdkVersion 14 targetSdkVersion 21 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } ... dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:21.0.+' //導入Appcompat依賴5.0的21並隨時獲取可用新版本 implementation 'com.android.support.v7.widget.SwichCompat'//導入支持MD的switch控件 implementation 'com.android.support:design.21' //導入21設計庫:參考連接:
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="AppTheme" parent="AppTheme.Base"/> <style name="AppTheme.Base" parent="Theme.AppCompat"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimary</item> <item name="windowNoTitle">true</item> <item name="windowActionBar">false</item> </style> </resources>
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="AppTheme" parent="AppTheme.Base"> <item name="android:windowContentTransitions">true</item> <item name="android:windowAllowEnterTransitionOverlap">true</item> <item name="android:windowAllowReturnTransitionOverlap">true</item> <item name="android:windowSharedElementEnterTransition">@android:transition/move</item> <item name="android:windowSharedElementExitTransition">@android:transition/move</item> </style> </resources>
參考連接:向前兼容this
apply plugin: 'com.android.application' allprojects { repositories { google() jcenter() } } ... dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:21.0.+' //導入Appcompat依賴5.0的21並隨時獲取可用新版本 implementation 'com.android.support.v7.widget.SwichCompat'//導入支持MD的switch控件 implementation 'com.android.support:design.21' //導入21設計庫 implementation 'com.android.support.constraint:constraint-layout:1.1.2' //implementation 'com.google.android.material:material:1.0.0-rc01'
參考連接-向前兼容-1
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/Theme.AppCompat.NoActionBar" /> <!--參考連接:關於toolbar-4--> <!--android:background="?attr/colorPrimaryDark"--> android:background="#3F51B5"> <!--Toolbar可自定義顏色--> </android.support.v7.widget.Toolbar>
@Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutResource()); //getLayoutResource()此處須要獲取佈局文件R.layout.…… Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); //主要關於Toolbar的代碼 if(toolbar != null) { setSupportActionBar(toolbar); } }
參考連接:Material Design
<com.google.android.material.navigation.NavigationView android:id="@+id/left_navigation_drawer" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" <!--layout_gravity指定重力--> app:headerLayout="@layout/navigation_header" <!--設置navigation頭佈局--> app:menu="@menu/my_navigation_items"> <!--設置navigation導航佈局--> <!--android:dividerHeight="0dp" android:background="#111"--/> </com.google.android.material.navigation.NavigationView> </android.support.v4.widget.DrawerLayout>
設置佈局,在相應目錄下新建文件:
layoutnavigation_header.xml
menumy_navigation_items
android:dividerHeight="0dp"
此處代碼連接爲開發者文檔,MD可能不須要兩行代碼。
此處連接爲開發者文檔。
<FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/decor_content_frame"> <!--主內容視圖必須爲第一個視圖,抽屜式導航必須位於內容頂部--> <android.support.v7.widget.Toolbar ... /> </FrameLayout>
參考連接:側滑菜單-1
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="?attr/colorPrimary" android:gravity="center" android:orientation="vertical" android:paddingBottom="50dp" android:paddingTop="50dp" android:theme="@style/ThemeOverlay.AppCompat.Dark"> <com.google.android.material.internal.VisibilityAwareImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/> <android.support.v7.widget.AppCompatTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:text="demo"/> </LinearLayout>
此處參考連接:側滑菜單-1,由於開發者文檔中使用Adpter方法實現填充,須要深刻了解Adpter,故未加入。
參考連接:側滑菜單-1
public class MainActivity extends AppCompatActivity { @Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private Toolbar toolbar; //此處Toolbar修改成本身習慣的寫法,爲變量 private String[] mTitles; //建立標題變量 private DrawerLayout mDrawerLayout; //建立抽屜視圖變量 private NavigationView mDrawerNavgation; //建立側滑菜單視圖變量 //private ActionBarDrawerToggle mDrawerToggle; 在後文中出現 //建立Toobar的子類做爲監聽器,須要在生命週期中調用togge //private CharSequence mDrawerTitle; //private CharSequence mTitle; ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //mTitles = R.layout.activity_main.getStringArray(R.array.Titles_array); //初始化界面 //此處Toolbar修改成本身習慣的寫法,實例化Toolbar寫一塊兒 Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); onCreateOptionsMenu(R.layout.activity_main); toolbar.setTitle("My Title"); setSupportActionBar(toolbar); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerNavgation = (NavigationView) findViewById(R.id.left_navigation_drawer); mDrawerNavgation.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_layout, mTitles)); //爲列表視圖設置適配器 mDrawerNavgation.setOnItemClickListener(new DrawerItemClickListener()); //調用接收點擊事件,設置點擊監聽器 } ... } }
private class DrawerItemClickListener implements NavigationView.OnItemClickListener { //開始處理導航事件:在用戶選擇某一項時實現接口更改內容視圖 @Override //這裏開始調用onItemClick public void onItemClick(AdapterView<?> parent, View view, int position, long id) { selectItem(position); } } private void selectItem(int position) { Fragment fragment = new Fragment(); //封裝一個新片斷並指定要根據位置顯示的 Bundle args = new Bundle(); args.putInt(Fragment.ARG_LIST_NUMBER, position); fragment.setArguments(args); FragmentManager fragmentManager = getFragmentManager(); //經過替換任何現有片斷插入片斷 fragmentManager.beginTransaction() //將不一樣的FrameLayout插入內容主視圖 .replace(R.id.decor_content_frame, fragment) .commit(); // Highlight the selected item, update the title, and close the drawer mDrawerNavgation.setItemChecked(position, true); setTitle(mTitles[position]); mDrawerLayout.closeDrawer(mDrawerNavgation); } @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); }
3.偵聽打開和關閉事件
public class MainActivity extends AppCompatActivity { private ActionBarDrawerToggle mDrawerToggle; //建立Toobar的子類做爲監聽器,須要在生命週期中調用togge private CharSequence mDrawerTitle; private CharSequence mTitle; ... @Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } ... mTitle = mDrawerTitle = getTitle(); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) { /** Called when a drawer has settled in a completely closed state. */ public void onDrawerClosed(View view) { super.onDrawerClosed(view); getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } /** Called when a drawer has settled in a completely open state. */ public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); //將抽屜切換設置爲DrawerListener getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } /* Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerNavgation); menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } }
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); //經過應用圖標打開或關閉抽屜導航欄 mDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description */ R.string.drawer_close /* "close drawer" description */ ) { public void onDrawerClosed(View view) { //當抽屜處於徹底關閉狀態時調用。 super.onDrawerClosed(view); //getActionBar().setTitle(mTitle); //設置標題 } public void onDrawerOpened(View drawerView) { //當抽屜處於徹底狀態時調用。 super.onDrawerOpened(drawerView); //getToolBar().setTitle(mDrawerTitle); //設置標題 } }; mDrawerLayout.setDrawerListener(mDrawerToggle); ////將抽屜切換設置爲DrawerListener getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); } @Override public boolean onPrepareOptionsMenu(Menu menu) { //每當咱們調用invalidateOptionsMenu()時調用 boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerNavgation); //若是導航抽屜已打開,請隱藏與內容視圖相關的操做項 menu.findItem(R.id.action_websearch).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } } @Override protected void onPostCreate(Bundle savedInstanceState) { //在生命週期中調用ActionBarDrawerToggle super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); ////在onRestoreInstanceState發生後同步切換狀態。 } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Pass the event to ActionBarDrawerToggle, if it returns // true, then it has handled the app icon touch event if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle your other action bar items... return super.onOptionsItemSelected(item); }
allprojects { repositories { google() jcenter() } } android { compileSdkVersion 21 defaultConfig { applicationId "product.penghaoxiong.com.androidquickcheck" minSdkVersion 14 targetSdkVersion 21 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:21.0.+' //導入Appcompat依賴5.0的21並隨時獲取可用新版本 implementation 'com.android.support.v7.widget.SwichCompat'//導入支持MD的switch控件 implementation 'com.android.support:design.21' //導入21設計庫 implementation 'com.android.support.constraint:constraint-layout:1.1.2' //implementation 'com.google.android.material:material:1.0.0-rc01' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }
layoutnavigation_header.xml
values/themes.xml
values-v21/themes.xml