连接工具栏和导航抽屉

时间:2016-04-19 08:01:52

标签: android navigation-drawer android-toolbar

我有几个活动,我想使用相同的导航抽屉。这是我与抽屉相关的Activity类代码的一部分:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

我打算制作一个DrawerActivity类,并从所有想要导航抽屉的活动中扩展它。因此,我必须将所有抽屉代码移动到DrawerActivity。

问题:

toolbarActionBarDrawerToggle的初始化非常重要。每个活动都有一个不同的工具栏,具体取决于该活动的需要。因此,工具栏布局必须保留在各自的布局xml文件中。我如何在DrawerActivity类中使用工具栏?

抽屉的布局xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">


<FrameLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/frame_layout"
    xmlns:android="http://schemas.android.com/apk/res/android">

</FrameLayout>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    app:itemBackground="@drawable/drawer_list_selector"
    style="@style/NavigationDrawer"
    app:headerLayout="@layout/sidenav_header"
    app:menu="@menu/side_navigation_menu"
    app:theme="@style/Drawer"/>

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

这是SideNavigation活动(我试图通过那些需要导航抽屉的类扩展):pastebin.com/hheMXku5

日志的主要陈述说:

  

引起:java.lang.NullPointerException:尝试调用虚方法&#39; void android.support.v7.app.ActionBar.setDisplayShowTitleEnabled(boolean)&#39;在空对象引用上

这是指向扩展SideNavigation类的其中一个活动类的onCreate的链接:pastebin.com/iKYXVbda

1 个答案:

答案 0 :(得分:0)

okey因此您想要使用带活动的抽屉。我在这里发布我的代码。我希望这会帮助你。

首先,您需要开发NavigationDrawer。我知道你可以自己做。

现在为示例 Home.java 创建子Activity,并使用抽屉扩展它,让我们说MainActivity.java

它会是这样的。

public class Home extends MainActivity{

     Toolbar toolbar;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
     }
}

现在我们通常会在setContentView中执行onCreate,这里做的就像这样。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getLayoutInflater().inflate(R.layout.home, frameLayout);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
}

frameLayout将成为您的容器,MainActivity

注意:不要忘记在主页活动中再选择ToolBar。因为它会覆盖MainActivity的工具栏。

修改 我发布我的整个代码请参考。虽然我已经使用了我的自定义导航抽屉,但它也可以与NavigationView一起使用。

<强> activity_main

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true" >

<RelativeLayout
    android:id="@+id/frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="false" >

    <!-- ToolBar of MainActivity -->

    <include
        android:id="@+id/toolbar_headers"
        layout="@layout/toolbar_header" />
</RelativeLayout>

<!-- here will be your NavigationView -->

<com.random.extraclasses.ScrimInsetsFrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:layout_marginRight="-8dp"
    android:elevation="8dp"
    android:fitsSystemWindows="true"
    app:insetForeground="#4000" >

    <include
        android:id="@+id/drawar_layout"
        layout="@layout/drawar_layout" />
</com.gujarat.property.extraclasses.ScrimInsetsFrameLayout>

<强> MainActivity.java

public class MainActivity extends AppCompatActivity implements OnClickListener {

     protected RelativeLayout frameLayout;
     protected DrawerLayout mDrawerLayout;
     protected ListView mDrawerList;
     protected ScrimInsetsFrameLayout mLayout;
     protected ActionBarDrawerToggle mDrawerToggle;
     protected static boolean isLaunch = true;

     Toolbar toolbar;

     private CharSequence mTitle;

     private String[] navMenuTitles;
     private TypedArray navMenuIcons;

     private ArrayList<NavDrawerItem> navDrawerItems;
     private NavDrawerListAdapter adapter;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

         navMenuIcons = getResources()
            .obtainTypedArray(R.array.nav_drawer_icons);

         frameLayout = (RelativeLayout) findViewById(R.id.frame_container);
         mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
         mDrawerList = (ListView) findViewById(R.id.list);
         mLayout = (ScrimInsetsFrameLayout) findViewById(R.id.container);

         toolbar = (Toolbar) findViewById(R.id.toolbar_headers);

         setSupportActionBar(toolbar);

         navDrawerItems = new ArrayList<NavDrawerItem>();

         navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
            .getResourceId(0, -1)));
         navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
            .getResourceId(1, -1)));
         navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
            .getResourceId(2, -1)));
         navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
            .getResourceId(3, -1)));

         navMenuIcons.recycle();

         adapter = new NavDrawerListAdapter(getApplicationContext(),
            navDrawerItems);
         mDrawerList.setOnItemClickListener(new OnItemClickListener() {
             @Override
             public void onItemClick(AdapterView<?> parent, View view,
                     int position, long id) {
                 selectedPos = position - 1;
                 displayView(position);
             }
         });

         mDrawerList.setAdapter(adapter);
         mDrawerList.setFocusable(false);

         getSupportActionBar().setDisplayHomeAsUpEnabled(true);
         getSupportActionBar().setHomeButtonEnabled(true);  

         mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.app_name) {
         };
         mDrawerLayout.setDrawerListener(mDrawerToggle);

         if (isLaunch) {
             isLaunch = false;
             displayView(0);
         }

     }

     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
         if (mDrawerToggle.onOptionsItemSelected(item)) {
             return true;
         }
         return super.onOptionsItemSelected(item);
     }

     private void displayView(int position) {

         mDrawerLayout.closeDrawer(mLayout);
         MainActivity.position = position;
         switch (position) {

         case 0:
             if (this.getClass().getSimpleName().equals("Home")) {
             } else {
                 Intent i = new Intent(this, Home.class);
                 startActivity(i);
                 overridePendingTransition(R.anim.fadein, R.anim.fadeout);
             }
             break;
         case 1:
             if (this.getClass().getSimpleName().equals("ForSale")) {
             } else {
                 Intent i = new Intent(this, ForSale.class);
                 startActivity(i);
                 overridePendingTransition(R.anim.fadein, R.anim.fadeout);
             }
             break;
         case 2:
              if (this.getClass().getSimpleName().equals("ForRent")) {
              } else {
                 Intent i = new Intent(this, ForRent.class);
                 startActivity(i);
                 overridePendingTransition(R.anim.fadein, R.anim.fadeout);
              } 
              break;
         case 3:
             if (this.getClass().getSimpleName().equals("NewProjects")) {
             } else {
                 Intent i = new Intent(this, NewProjects.class);
                 startActivity(i);
                 overridePendingTransition(R.anim.fadein, R.anim.fadeout);
             }
             break;
          default:
             break;
         }
     }

     @Override
     public void setTitle(CharSequence title) {
         mTitle = title;
         getSupportActionBar().setTitle(mTitle);
     }

     @Override
     protected void onPostCreate(Bundle savedInstanceState) {
         super.onPostCreate(savedInstanceState);
         mDrawerToggle.syncState();
     }

     @Override
     public void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         mDrawerToggle.onConfigurationChanged(newConfig);
     }

     @Override
     public void onClick(View v) {

     }
 }

最后 Home.java

public class Home extends MainActivity implements OnClickListener {

Toolbar toolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getLayoutInflater().inflate(R.layout.home, frameLayout);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setTitle("");
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    if (mDrawerLayout.isDrawerOpen(mLayout)) {
        isLaunch = false;
        mDrawerLayout.closeDrawer(mLayout);
    } else {
        finishAffinity();
    }
}

仅供参考 home.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:id="@+id/main"
     android:layout_width="match_parent"
     android:layout_height="match_parent" >

     <RelativeLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:layout_below="@+id/toolbar"
         android:background="@drawable/back51" >

        <TextView
             android:id="@+id/etSearch"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_marginLeft="10dp"
             android:background="@android:color/transparent"
             android:text="Search Property"
             android:textColor="#666666" />
     </RelativeLayout>

     <android.support.v7.widget.Toolbar
         android:id="@+id/toolbar"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         app:layout_scrollFlags="scroll|enterAlways"
         android:background="@color/toobar"
         android:minHeight="?attr/actionBarSize"
         android:theme="@style/ThemeOverlay.AppCompat.Dark"
         app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >
     </android.support.v7.widget.Toolbar>

</RelativeLayout>

我希望这会帮助你。