Почему фрагменты не отображаются из моего навигационного ящика? - PullRequest
1 голос
/ 22 января 2020

Здесь, ребята, я, честно говоря, пытался сделать это в разные стороны, но по некоторым причинам разные фрагменты просто не будут отображаться должным образом. Я дошел до точки, где обнаруживается фрагмент, но он находится поверх фрагмента дома. Я так расстроен Я занимался этим в течение ДНЕЙ

Вот важная часть MainActivity. java

 @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Toolbar toolbar = findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);


        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();


        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new HomeFragment()).commit();
            navigationView.setCheckedItem(R.id.nav_home);
        }
    }





        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
     /*   mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_members, R.id.nav_map,
                R.id.nav_news, R.id.nav_livestream, R.id.nav_election,
                R.id.nav_share, R.id.nav_login)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

        navigationView.bringToFront(); */

      // navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {



    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                switch (menuItem.getItemId()) {
                    case R.id.nav_home:
                        Toast.makeText(getApplicationContext(), "Home is selected", Toast.LENGTH_LONG).show();
                        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                                new HomeFragment()).commit();
                        break;

                    case R.id.nav_members:
                        Toast.makeText(getApplicationContext(), "Members are selected",Toast.LENGTH_LONG).show();

                        getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,
                                new MembersFragment()).commit();
                        break;

                    case R.id.nav_map:
                        Toast.makeText(getApplicationContext(), "Map is selected", Toast.LENGTH_LONG).show();
                        FragmentManager mapfm= getSupportFragmentManager();
                        MapFragment mapFragment = new MapFragment();
                        mapfm.beginTransaction().replace(R.id.drawer_layout, mapFragment).commit();


                        break;

                    case R.id.nav_news:
                        Toast.makeText(getApplicationContext(), "News is selected", Toast.LENGTH_LONG).show();
                        Intent newsStart =new Intent(MainActivity.this, MainActivityGaeilge.class);
                        startActivity(newsStart);
                        break;

                    case R.id.nav_livestream:
                        Toast.makeText(getApplicationContext(), "Livestream is selected", Toast.LENGTH_LONG).show();

                       getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,
                               new LivestreamFragment()).commit();
                        break;

                    case R.id.nav_election:
                        Toast.makeText(getApplicationContext(), "Election info is selected", Toast.LENGTH_LONG).show();
                        //Intent electionopen = new Intent(MainActivity.this, ElectionFragment.class);
                       // startActivity(electionopen);

                        FragmentManager electionfm= getSupportFragmentManager();
                        ElectionFragment electionFragment = new ElectionFragment();
                        electionfm.beginTransaction().replace(R.id.home_page, electionFragment).commit();
                        break;


                    case R.id.nav_share:
                        Toast.makeText(getApplicationContext(), "Share is selected", Toast.LENGTH_LONG).show();
                        getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment,
                                new SendFragment()).commit();
                        //Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
                        //Intent sharestart=new Intent(MainActivity.this,this.class);
                       // startActivity(sharestart);
                        break;

                    case R.id.nav_login:
                        Toast.makeText(getApplicationContext(), "Login is selected", Toast.LENGTH_LONG).show();
                        break;



                   // case R.id.nav_election:
                      //  Intent electionopen = new Intent(MainActivity.this, ElectionFragment.class);
                     //   startActivity(electionopen);
                }

                drawer.closeDrawer(GravityCompat.START);

                return true;
            }

            @Override
            public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
            }

Вот Activity_main. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.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:context=".MainActivity"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

     <com.google.android.material.navigation.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:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.drawerlayout.widget.DrawerLayout>

Вот app_bar_main. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
    android:id="@+id/home_page"
    tools:context=".MainActivity"
    android:orientation="vertical">

        <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </com.google.android.material.appbar.AppBarLayout>

   <include layout="@layout/content_main" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

А вот content_main. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:showIn="@layout/app_bar_main">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="56dp"
        android:layout_height="27dp"
        android:layout_marginStart="82dp"
        android:layout_marginTop="227dp"
        android:layout_marginEnd="273dp"
        android:layout_marginBottom="477dp"
        android:text="Text: "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="168dp"
        android:layout_marginTop="218dp"
        android:layout_marginEnd="30dp"
        android:layout_marginBottom="466dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="138dp"
        android:layout_marginTop="328dp"
        android:layout_marginEnd="149dp"
        android:layout_marginBottom="355dp"
        android:onClick="OnLogin"
        android:text="Login Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="80dp"
        android:layout_marginTop="274dp"
        android:layout_marginEnd="265dp"
        android:layout_marginBottom="438dp"
        android:onClick="OnLogin"
        android:text="Password:"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="169dp"
        android:layout_marginTop="268dp"
        android:layout_marginEnd="29dp"
        android:layout_marginBottom="418dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

ПОЖАЛУЙСТА, ПОМОГИТЕ IM НАСТОЛЬКО НАПРЯЖЕН

1 Ответ

0 голосов
/ 22 января 2020

В настоящее время у вас есть два контейнера, в которые Fragment может go:

  • Вы используете поддержку FragmentManager по всему MainActivity с FrameLayout с android:id="@+id/fragment_container" для добавления и замены различных Fragment s

  • Кажется, вы настроили навигационную диаграмму, по крайней мере, есть NavHostFragment в content_main. xml и некоторый код, связанный с NavController в комментариях в MainActivity

Похоже, вы добавляете HomeFragment дважды: один раз в качестве начала Fragment на навигационном графике а в другой раз в onCreate() через службу поддержки FragentManager

Поэтому, когда вы перемещаетесь по своему приложению, вы видите Fragment s, отображаемые поверх экземпляра HomeFragment в NavHostFragment

Решение: используйте поддержку FragmentManager или NavController во всем приложении и удалите контейнер, принадлежащий другому подходу (NavHostFragment или FrameLayout)

Следующие предложения предполагают, что вы хотите использовать FragmentManager:

Удалите FrameLayout, служащий контейнером для * 10 45 * с из activity_main. xml:

<androidx.drawerlayout.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:context=".MainActivity"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

     <com.google.android.material.navigation.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" />

</androidx.drawerlayout.widget.DrawerLayout>

... и добавьте его к content_main. xml вместо NavHostFragment

<androidx.constraintlayout.widget.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:showIn="@layout/app_bar_main">

  <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="56dp"
        android:layout_height="27dp"
        android:layout_marginStart="82dp"
        android:layout_marginTop="227dp"
        android:layout_marginEnd="273dp"
        android:layout_marginBottom="477dp"
        android:text="Text: "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="168dp"
        android:layout_marginTop="218dp"
        android:layout_marginEnd="30dp"
        android:layout_marginBottom="466dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="138dp"
        android:layout_marginTop="328dp"
        android:layout_marginEnd="149dp"
        android:layout_marginBottom="355dp"
        android:onClick="OnLogin"
        android:text="Login Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="80dp"
        android:layout_marginTop="274dp"
        android:layout_marginEnd="265dp"
        android:layout_marginBottom="438dp"
        android:onClick="OnLogin"
        android:text="Password:"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="169dp"
        android:layout_marginTop="268dp"
        android:layout_marginEnd="29dp"
        android:layout_marginBottom="418dp"
        android:ems="10"
        android:inputType="textPersonName"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Обратите внимание, что вы можете удалить файл res / navigation / mobile-navigation. xml, поскольку он использовался только NavHostFragment

...