Android App中DrawerLayout抽屜效果的菜單編寫執行個體_php技巧

來源:互聯網
上載者:User

抽屜效果的導覽功能表
看了很多應用,覺得這種側滑的抽屜效果的菜單很好。

不用切換到另一個頁面,也不用去按菜單的硬體按鈕,直接在介面上一個按鈕點擊,菜單就滑出來,而且感覺能放很多東西。
庫的引用:
首先, DrawerLayout這個類是在Support Library裡的,需要加上android-support-v4.jar這個包。

然後程式中用時在前面匯入import android.support.v4.widget.DrawerLayout;

如果找不到這個類,首先用SDK Manager更新一下Android Support Library,然後在Android SDK\extras\android\support\v4路徑下找到android-support-v4.jar,複製到項目的libs路徑,將其Add to Build Path.

代碼1
布局:

<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" >  <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" >    <!-- The main content view -->    <!-- main content must be the first element of DrawerLayout because it will be drawn first and drawer must be on top of it -->    <FrameLayout      android:id="@+id/content_frame"      android:layout_width="match_parent"      android:layout_height="match_parent" />    <!-- The navigation drawer -->    <ListView      android:id="@+id/left_drawer"      android:layout_width="240dp"      android:layout_height="match_parent"      android:layout_gravity="left"      android:background="#111"      android:choiceMode="singleChoice"      android:divider="@android:color/transparent"      android:dividerHeight="0dp" />  </android.support.v4.widget.DrawerLayout></RelativeLayout> 

  DrawerLayout的第一個子項目是主要內容,即抽屜沒有開啟時顯示的布局。這裡採用了一個FrameLayout,裡面什麼也沒放。

  DrawerLayout的第二個子項目是抽屜中的內容,即抽屜布局,這裡採用了一個ListView。

主要的Activity(從官方執行個體中扒出來的):

package com.example.hellodrawer;import android.os.Bundle;import android.app.Activity;import android.content.res.Configuration;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ArrayAdapter;import android.widget.ListView;import android.support.v4.app.ActionBarDrawerToggle;import android.support.v4.view.GravityCompat;import android.support.v4.widget.DrawerLayout;public class HelloDrawerActivity extends Activity{  private String[] mPlanetTitles;  private DrawerLayout mDrawerLayout;  private ActionBarDrawerToggle mDrawerToggle;  private ListView mDrawerList;  @Override  public void onCreate(Bundle savedInstanceState)  {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_hello_drawer);    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);    // init the ListView and Adapter, nothing new    initListView();    // set a custom shadow that overlays the main content when the drawer    // opens    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,        GravityCompat.START);    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)      {        invalidateOptionsMenu(); // creates call to                      // onPrepareOptionsMenu()      }      /** Called when a drawer has settled in a completely open state. */      public void onDrawerOpened(View drawerView)      {        invalidateOptionsMenu(); // creates call to                      // onPrepareOptionsMenu()      }    };    // Set the drawer toggle as the DrawerListener    mDrawerLayout.setDrawerListener(mDrawerToggle);    // enable ActionBar app icon to behave as action to toggle nav drawer    getActionBar().setDisplayHomeAsUpEnabled(true);    // getActionBar().setHomeButtonEnabled(true);    // Note: getActionBar() Added in API level 11  }  private void initListView()  {    mDrawerList = (ListView) findViewById(R.id.left_drawer);    mPlanetTitles = getResources().getStringArray(R.array.planets_array);    // Set the adapter for the list view    mDrawerList.setAdapter(new ArrayAdapter<String>(this,        R.layout.list_item, mPlanetTitles));    // Set the list's click listener    mDrawerList.setOnItemClickListener(new OnItemClickListener()    {      @Override      public void onItemClick(AdapterView<?> parent, View view,          int position, long id)      {        // Highlight the selected item, update the title, and close the        // drawer        mDrawerList.setItemChecked(position, true);        setTitle(mPlanetTitles[position]);        mDrawerLayout.closeDrawer(mDrawerList);      }    });  }  @Override  protected void onPostCreate(Bundle savedInstanceState)  {    super.onPostCreate(savedInstanceState);    // Sync the toggle state after onRestoreInstanceState has occurred.    mDrawerToggle.syncState();  }  @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);  }}

比較糾結的是用了Level 11的一個API,這樣minSdkVersion就有限制,不能太低。

圖片資源Android官網樣本處提供下載了。

程式運行後效果如下:
抽屜開啟前:

抽屜開啟後:

代碼2
今天又看了一下DrawerLayout的類,發現有很多方法可以直接用的。

重新試了一下,其實不用上面那麼麻煩,隨便自己定義一個按鈕控制抽屜的開啟就行:

布局:

<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"  android:paddingBottom="@dimen/activity_vertical_margin"  android:paddingLeft="@dimen/activity_horizontal_margin"  android:paddingRight="@dimen/activity_horizontal_margin"  android:paddingTop="@dimen/activity_vertical_margin"  tools:context=".DrawerActivity" >  <android.support.v4.widget.DrawerLayout    android:id="@+id/drawer_layout"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <!-- The main content view -->    <FrameLayout      android:id="@+id/content_frame"      android:layout_width="match_parent"      android:layout_height="match_parent" >      <Button        android:id="@+id/btn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="open"         />    </FrameLayout>    <!-- The navigation drawer -->    <ListView      android:id="@+id/left_drawer"      android:layout_width="240dp"      android:layout_height="match_parent"      android:layout_gravity="start"      android:background="#111"      android:choiceMode="singleChoice"      android:divider="@android:color/transparent"      android:dividerHeight="0dp" />  </android.support.v4.widget.DrawerLayout></RelativeLayout>

 
主要代碼:

package com.example.hellodrawer;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 DrawerActivity extends Activity{  private DrawerLayout mDrawerLayout = null;  @Override  protected void onCreate(Bundle savedInstanceState)  {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_drawer);    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);      }    });  }}

使用Toolbar + DrawerLayout快速實現高大上菜單側滑
如果你有在關注一些遵循最新的Material Design設計規範的應用的話(如果沒有,假設你有!),也許會發現有很多使用了看起來很舒服、很高大上的側滑菜單動畫效果,樣本如下(via 參考2):

今天就來使用官方支援庫來快速實現這類效果,需要使用到Toolbar和DrawerLayout,詳細步驟如下:(如果你還不知道這兩個Widget,先自己Google吧~)
首先需要添加appcompat-v7支援:

如果是在Android Studio 1.0 RC4上建立的項目,預設已經添加了appcompat-v7支援了,如果不是最新版AS則需要在build.gradle中添加如下代碼:

dependencies {  ...//其他代碼  compile 'com.android.support:appcompat-v7:21.0.2'}

添加完成後需要同步一下gradle

添加Toolbar:

由於Toolbar是繼承自View,所以可以像其他標準控制項一樣直接主布局檔案添加Toolbar,但是為了提高Toolbar的重用效率,可以在layout建立一個custom_toolbar.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>  <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:id="@+id/tl_custom"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="?attr/colorPrimary"    android:minHeight="?attr/actionBarSize"    android:popupTheme="@style/ThemeOverlay.AppCompat.Light"    app:theme="@style/ThemeOverlay.AppCompat.ActionBar"></android.support.v7.widget.Toolbar>

說明:

android.support.v7.widget.Toolbar - 當然如果只在Lollipop中可以直接使用Toolbar而不需要加上v7支援
xmlns:app - 自訂xml命名控制項,在AS中可以直接指定res-auto而不需要使用完整包名
android:background 和 android:minHeight 均可以在styles.xml中聲明
添加DrawerLayout:

和Toolbar類似,為了提高代碼重用效率,可以在layout中建立一個custom_drawerlayout.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/dl_left"    android:layout_width="match_parent"    android:layout_height="match_parent">  <!--主布局-->  <LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent">    <ImageView      android:id="@+id/iv_main"      android:layout_width="100dp"      android:layout_height="100dp" />  </LinearLayout>  <!--側滑菜單-->  <LinearLayout    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="#fff"    android:layout_gravity="start">    <ListView      android:id="@+id/lv_left_menu"      android:layout_width="match_parent"      android:layout_height="match_parent"      android:divider="@null"      android:text="DrawerLayout" />  </LinearLayout></android.support.v4.widget.DrawerLayout>

Drawerlayout標籤中有兩個子節點,一個是左邊菜單,一個是主布局,另外需要在左邊菜單起始位置設定為android:layout_gravity="start"

實現activity_main.xml:

<LinearLayout 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"  android:orientation="vertical"  tools:context=".MainActivity">    <!--Toolbar-->    <include layout="@layout/custom_toolbar" />    <!--DrawerLayout-->    <include layout="@layout/custom_drawerlayout" /></LinearLayout>

直接使用include標籤,簡潔明了

完善Java代碼:

public class MainActivity extends ActionBarActivity {  //聲明相關變數  private Toolbar toolbar;  private DrawerLayout mDrawerLayout;  private ActionBarDrawerToggle mDrawerToggle;  private ListView lvLeftMenu;  private String[] lvs = {"List Item 01", "List Item 02", "List Item 03", "List Item 04"};  private ArrayAdapter arrayAdapter;  private ImageView ivRunningMan;  private AnimationDrawable mAnimationDrawable;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    findViews(); //擷取控制項    //京東RunningMan動畫效果,和本次Toolbar無關    mAnimationDrawable = (AnimationDrawable) ivRunningMan.getBackground();    mAnimationDrawable.start();    toolbar.setTitle("Toolbar");//設定Toolbar標題    toolbar.setTitleTextColor(Color.parseColor("#ffffff")); //設定標題顏色    setSupportActionBar(toolbar);    getSupportActionBar().setHomeButtonEnabled(true); //設定返回鍵可用    getSupportActionBar().setDisplayHomeAsUpEnabled(true);    //建立返回鍵,並實現開啟關/閉監聽    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.open, R.string.close) {      @Override      public void onDrawerOpened(View drawerView) {        super.onDrawerOpened(drawerView);        mAnimationDrawable.stop();      }      @Override      public void onDrawerClosed(View drawerView) {        super.onDrawerClosed(drawerView);        mAnimationDrawable.start();      }    };    mDrawerToggle.syncState();    mDrawerLayout.setDrawerListener(mDrawerToggle);    //設定菜單列表    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lvs);    lvLeftMenu.setAdapter(arrayAdapter);  }  private void findViews() {    ivRunningMan = (ImageView) findViewById(R.id.iv_main);    toolbar = (Toolbar) findViewById(R.id.tl_custom);    mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_left);    lvLeftMenu = (ListView) findViewById(R.id.lv_left_menu);  }}

當然比較重要還有styles.xml和colors.xml,具體如下: 

<resources>  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">    <!--狀態列顏色-->    <item name="colorPrimaryDark">@color/Indigo_colorPrimaryDark</item>    <!--Toolbar顏色-->    <item name="colorPrimary">@color/Indigo_colorPrimary</item>    <!--返回鍵樣式-->    <item name="drawerArrowStyle">@style/AppTheme.DrawerArrowToggle</item>    </style>    <style name="AppTheme.DrawerArrowToggle" parent="Base.Widget.AppCompat.DrawerArrowToggle">    <item name="color">@android:color/white</item>  </style></resources><?xml version="1.0" encoding="utf-8"?><resources>  <color name="Indigo_colorPrimaryDark">#303f9f</color>  <color name="Indigo_colorPrimary">#3f51b5</color>  <color name="Indigo_nav_color">#4675FF</color></resources>

到此就實現了高大上菜單側滑,最終效果如下(註:在Yosemite上貌似直接Record手機螢幕貌似不起作用,而且動畫由於幀率原因無法即時,就先這樣看吧~)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.