【问题标题】:Navigation Drawer App does not change fragments when clicked导航抽屉应用程序在单击时不会更改片段
【发布时间】:2019-12-06 15:28:09
【问题描述】:

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

主活动:


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>

content_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>

【问题讨论】:

  • 你能分享一些代码吗?
  • 贴出您的抽屉式导航栏项目的点击代码。
  • 当然,我以为我做到了。对不起,我会修改问题
  • onNavigationItemSelected() 方法中,您在两种情况下都替换了相同的片段。

标签: java android android-studio android-fragments navigation-drawer


【解决方案1】:

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

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;

这可能对你有用

【讨论】:

    【解决方案2】:

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

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

    1. 如果你使用的是java,像这个方法一样使用

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

    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 类,第二个是标题(标题是可选的,如果你使用或不使用)

    声明全局变量

    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)
        }
    }
    

    【讨论】:

      【解决方案3】:

      因为你用同一个类替换片段:

      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;
      

      【讨论】:

      • 非常感谢,但这不是问题,实际上从来没有改变过主页。我的意思是,在 CulturaClass 中,我加载了具有 Button 和 TextView 的 fragment_cultura 但我看不到它们
      • 不,你再次加载相同的类。
      • 我按照您的建议更改了代码,但应用程序没有任何变化
      • @Blogger 我添加了 CulturaClass() 代码。无论如何都没有改变:(
      • 那就换别的班!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多