DrawaerLayout.onDrawerOpened从不叫
问题描述:
我想改变我的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>
答
在构造函数
你应该叫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()
谢谢,我忽略了这个 – rommex
UPD只是根据你的建议 - 仍然onDrawerOpened没有被调用。 – rommex
更新您的问题并向我显示您对代码所做的更改 – Blackbelt