导航抽屉应用程序在单击时不会更改片段

Navigation Drawer App does not change fragments when clicked

早上好,我是一名新手程序员,我使用 Navigation Drawer Android Studio Activity 开始。当我编译时一切正常,但是当我使用该应用程序并单击不同的选项时,没有任何反应(我的意思是布局没有改变并保持在 activity_main.xml 上)。我寻找其他问题,但(我认为)没有人遇到过我的问题。

主要Activity:


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private DrawerLayout drawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Ma giusto a provare", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        switch(item.getItemId()) {
            case R.id.nav_home:
                ft.replace(R.id.fragment_container
                        , new CulturaClass()).commit();
                break;
            case R.id.nav_gallery:
                ft.replace(R.id.fragment_container
                        , new CulturaClass()).commit();
                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    }

main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>

内容_main.xml


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/app_bar_main">

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>
</android.support.constraint.ConstraintLayout>

activity_main_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_menu_camera"
            android:title="@string/menu_home" />
        <item
            android:id="@+id/nav_gallery"
            android:icon="@drawable/ic_menu_gallery"
            android:title="@string/menu_Cultura" />
        <item
            android:id="@+id/nav_slideshow"
            android:icon="@drawable/ic_menu_slideshow"
            android:title="@string/menu_organizer" />
        <item
            android:id="@+id/nav_tools"
            android:icon="@drawable/ic_menu_manage"
            android:title="@string/menu_tools" />
    </group>

    <item android:title="Communicate">
        <menu>
            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="@string/menu_share" />
            <item
                android:id="@+id/nav_send"
                android:icon="@drawable/ic_menu_send"
                android:title="@string/menu_send" />
        </menu>
    </item>

</menu>

fragment_cultura.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cultura generale!"
        tools:layout_editor_absoluteX="171dp"
        tools:layout_editor_absoluteY="320dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="VVVVai!"
        tools:layout_editor_absoluteX="161dp"
        tools:layout_editor_absoluteY="403dp" />
</android.support.constraint.ConstraintLayout>

CulturaClass.java

public class CulturaClass extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_cultura,container,false);
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="hello" />

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

Because you are replacing fragment with same class:

case R.id.nav_home:
     ft.replace(R.id.fragment_container
            , new CulturaClass()).commit();    //Same Class  
     break;
case R.id.nav_gallery:
     ft.replace(R.id.fragment_container
           , new CulturaClass()).commit();    //Same Class
break;

你可以使用常用的函数或方法简单易行地做这件事,而且你永远不会出错。

你有两种选择来使用这个,一种是使用 JAVA,第二种是 KOTLIN 我在下面写的第一个方法检查这个:

  1. 如果你正在使用java,请像这样使用

首先,创建一个函数,即命名为 setFragment 并传递参数 Fragment class,第二个是标题(如果您使用或不使用,标题是可选的) 声明全局变量

private Fragment fragment = null;

//create function for replace fragment
private void setFragment(Fragment fragmentName, String title) {
    fragment = fragmentName;
    if (fragment != null) {
        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.framelayout, fragment, fragment.getTag()).commit();
    }

    setTitle("Dashboard");

    // Close the navigation drawer
    drawerLayout.closeDrawers();
}
  1. 如果您正在使用 KOTLIN:

首先,创建一个函数,即命名为 openFragment 并传递参数 Fragment class,第二个是标题(如果您使用或不使用,标题是可选的)

声明全局变量

private var fragment: Fragment? = null

//create function for replace fragment
fun openFragment(fragmentClass: Fragment, titleName: String) {
    //pass the current fragment class name which you replace
    fragment = fragmentClass
    //check first fragment is null or not
    if (fragment != null) {
        val fragmentManager = supportFragmentManager
        fragmentManager.beginTransaction()
            .replace(R.id.framelayout, fragment!!, fragment!!.tag).commit()
    }

    title = titleName // replace the titlename 
    //check the drawerLayout close or not
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START)
    }
}

而不是 R.id.fragment_containeractivity_main.xml 中为 FrameLayout 提供名称,并在替换片段时传递该名称,即

case R.id.nav_home:
     ft.replace(R.id.<name_of_framelayout>, new CulturaClass()).commit();
     break;

case R.id.nav_gallery:
     ft.replace(R.id.<name_of_framelayout>, new CulturaClass()).commit();
     break;

这可能适合你