所有活动onNavigationItemSelected事件中的导航抽屉都不起作用

时间:2016-04-13 15:23:13

标签: android

我创建了一个BaseActivity,并重写了setContentView,这是BaseActivity代码

public class BaseActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

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

    }

    @Override
    public void setContentView(int layoutResID)
    {
        DrawerLayout fullView = (DrawerLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
        FrameLayout activityContainer = (FrameLayout) fullView.findViewById(R.id.activity_content);
        getLayoutInflater().inflate(layoutResID, activityContainer, true);
        super.setContentView(fullView);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Log.i("NAV","nav selected");
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.activity_container);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}

并且BaseActivity的xml就像这样

<android.support.v4.widget.DrawerLayout
    android:id="@+id/activity_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@+id/activity_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/activity_side_menu_drawer"/>

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

在MainActivity上我像这样扩展了这个

public class MainActivity extends BaseActivity{

}

实际上导航显示效果不错,但onNavigationItemSelected无效!!

我试图记录或Toast没有任何工作 怎么了?

提前感谢。

1 个答案:

答案 0 :(得分:0)

您需要致电setNavigationItemSelectedListener

需要在NavigationView

上调用此方法

首先通过NavigationView

获取findViewById(R.id.navigationView)

最后致电navigationView.setNavigationItemSelectedListener(this)

这将告诉您的导航视图,所选项目的监听器是BaseActivity