如何在android中创建自定义导航抽屉?

时间:2014-04-16 08:44:52

标签: android android-actionbar navigation-drawer

嗨我正在做一个Android项目,我希望在所有页面中显示导航抽屉。在主屏幕中,想要在左侧顶部显示导航抽屉,在屏幕右上方显示登录应用程序的用户的图片。

enter image description here

如果有人知道用导航抽屉创建自定义操作栏,请帮助我。

1 个答案:

答案 0 :(得分:1)

您需要在菜单文件夹中为右侧的图像添加菜单文件。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+id/your_id"
    android:icon="@drawable/the image you want"
    android:orderInCategory="100"
    android:showAsAction="always"
    android:title="Your title"/>
</menu>

然后在您要将此代码放入(onCreate外部)的活动中:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);

    return true;
}

这会将菜单置于顶部。

现在,对于右侧的图像(三行),将其放入xml中以进行活动(这也会在侧面添加抽屉,您可以像任何列表视图一样自定义它)

<android.support.v4.widget.DrawerLayout      xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstActivity" >

<!-- The main content goes here -->

 <!-- The navigation drawer -->

<ListView  
    android:id="@+id/drawer1"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#FFFFFF"
    android:choiceMode="singleChoice"
    android:divider="#FF0000"
    android:dividerHeight="1dp"
    android:paddingLeft="15sp"
    android:paddingRight="15sp" />

</android.support.v4.widget.DrawerLayout>

然后把这部分放在你的java中。你需要从某个地方获得ic抽屉图像,但是那里到处都是google for it。

    final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout1);
    actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
    drawer, /* DrawerLayout object */
    R.drawable.ic_drawer, /* This is the image for top left*/
    R.string.drawer_open, /* "open drawer" description */
    R.string.drawer_close /* "close drawer" description */
    );