2015-11-11 23 views
1

我想改變我的DrawerLayout中的textview。所以我用我自己的課程擴展它。問題是當我調試這段代碼時,onDrawerOpened永遠不會被調用,特別是在打開抽屜時。DrawaerLayout.onDrawerOpened從不叫

import android.support.v4.widget.DrawerLayout; 

    public class MyDrawerLayout extends DrawerLayout implements DrawerLayout.DrawerListener { 
    //Context context; 

    public MyDrawerLayout(Context c) { 
     this(c, null); 
    } 

    public MyDrawerLayout(Context c, AttributeSet attrs) { 
     this(c, attrs, 0); 
    } 

    public MyDrawerLayout (Context c, AttributeSet attrs, int defStyle) { 
     super (c, attrs, defStyle); 
     setDrawerListener(this); 
    } 

    public void onDrawerOpened(View drawerView) { 

     LinearLayout root = (LinearLayout)(drawerView.findViewById(R.id.root)); 
     TextView t = (TextView) (root.findViewById(R.id.textView)); 
     t.setText(((MainActivity) MainActivity.main_activity).globalScenarioName); 
     Snackbar.make(((MainActivity)MainActivity.main_activity).container, "NAVVIEW Open", Snackbar.LENGTH_LONG) 
       .setAction("Action", null).show(); 
    } 

    public void onDrawerSlide (View drawerView, float slide) { 

    } 

    public void onDrawerClosed (View drawerView) { 

    } 

    public void onDrawerStateChanged (int newState) {} 
} 

的activity_main.xml中佈局如下標準:

<net.mycom.myproject.widget.MyDrawerLayout 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"> 

    <include 
     layout="@layout/app_bar_main" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <android.support.design.widget.NavigationView 
     android:id="@+id/nav_view" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:fitsSystemWindows="true" 
     app:headerLayout="@layout/nav_header_main" 
     app:menu="@menu/activity_main_drawer" /> 

</net.mycom.myproject.widget.MyDrawerLayout> 

回答

1
在構造函數

你應該叫setDrawerListener(this),登記類作爲監聽器,因爲它是implmenting DrawerLayout.DrawerListener

public MyDrawerLayout(Context c) { 
    this(c, null); 
} 

public MyDrawerLayout(Context c, AttributeSet attrs) { 
    this(c, attrs, 0); 
} 

public MyDrawerLayout (Context c, AttributeSet attrs, int defStyle) { 
    super (c, attrs, defStyle); 
    setDrawerListener(this); 
} 

你不要保留對上下文的引用。查看有方法getContext()

+0

謝謝,我忽略了這個 – rommex

+0

UPD只是根據你的建議 - 仍然onDrawerOpened沒有被調用。 – rommex

+0

更新您的問題並向我顯示您對代碼所做的更改 – Blackbelt