我想在DrawerLayout中更改textview。所以我用自己的课程扩展它。问题是当我调试这段代码时,永远不会调用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>
答案 0 :(得分:1)
在您的构造函数中,您应该调用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()