我想在android中的导航抽屉中添加Fragment,我尝试了下面的代码,但它没有发生

时间:2016-04-16 18:56:06

标签: android android-fragments

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_downloads) {
        Intent i = new Intent(this,DownloadPage.class);
        startActivity(i);
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_settings) {

        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) { // here i want to add fragment
                Manage manage = new Manage();
                FragmentTransaction transaction = fm.beginTransaction();
                transaction.add(R.id.downfragment, manage, "Settings");
                transaction.commit();

            }
        };
    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }
}

1 个答案:

答案 0 :(得分:0)

为此,您不需要另外View.OnClickListener,当您点击抽屉项目时onNavigationItemSelected() 已经调用。因此,只需删除listener代码,如下所示:

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_downloads) {
        Intent i = new Intent(this,DownloadPage.class);
        startActivity(i);
   } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_settings) {

        Manage manage = new Manage();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.add(R.id.downfragment, manage, "Settings");
        transaction.commit();


} else if (id == R.id.nav_share) {

} else if (id == R.id.nav_send) {

}
}