Android 从未调用DrawaerLayout.onDrawerOpened
我想更改抽屉布局中的文本视图。所以我用我自己的类来扩展它。问题是当我调试这段代码时,永远不会调用onDrawerOpened,特别是当抽屉被打开时Android 从未调用DrawaerLayout.onDrawerOpened,android,navigation,listener,drawer,Android,Navigation,Listener,Drawer,我想更改抽屉布局中的文本视图。所以我用我自己的类来扩展它。问题是当我调试这段代码时,永远不会调用onDrawerOpened,特别是当抽屉被打开时 import android.support.v4.widget.DrawerLayout; public class MyDrawerLayout extends DrawerLayout implements DrawerLayout.DrawerListener { //Context context; pu
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>
在构造函数中,您应该调用
setDrawerListener(this)
,将类注册为侦听器,因为它正在实现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);
}
您不需要保留对上下文的引用。View的方法
getContext()
UPD刚刚按照您的建议执行--仍然未调用onDrawerOpened。请更新您的问题并向我显示您对代码所做的更改。您如何知道未调用onDrawerOpened?您是否也可以从外部调用setDrawerListener
?首先,文本视图不会被修改。其次,在调试模式下,永远不会到达停止点。我从您那里了解了setDrawerListener()方法,因此它是独一无二的。UPD构造函数被执行,顺便说一句。如果您没有覆盖引用并且在布局中使用MyDrawerLayout
,那么没有理由不调用侦听器。发布更多代码。