【问题标题】:How do I fix this error in navController MainActivity?如何在 navController MainActivity 中修复此错误?
【发布时间】:2021-02-08 20:39:58
【问题描述】:

Illegal State Exception 错误...我无法理解...如何修复 MainActivity 没有导航控制器?

我刚刚编译了我的代码,当我尝试启动应用程序时收到错误消息。我目前正在尝试为我的课程项目设置片段。不知道为什么我会得到这个输出......

错误:-

 Caused by: java.lang.IllegalStateException: Activity com.example.instagramclone.MainActivity@6a5f3da does not have a NavController set on 2131362023

我的 MainAcivity.java:-

package com.example.instagramclone;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.example.instagramclone.ui.home.HomeFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView navView = findViewById(R.id.nav_view);
        NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);

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

        ImageView cameraToolbar = toolbar.findViewById(R.id.camera);

        cameraToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this, "CAMERA", Toast.LENGTH_SHORT).show();

            }
        });

        navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                if(menuItem.getItemId() == R.id.navigation_home)
                {

                    HomeFragment homeFragment = new HomeFragment();
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.nav_host_fragment , homeFragment);
                    transaction.commit();
                }

                else if (menuItem.getItemId() == R.id.search) {
                    Toast.makeText(MainActivity.this, "SEARCH", Toast.LENGTH_SHORT).show();
                }



                return true;
            }
        });
    }
}                

我的 activity_main.xml:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="5dp">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@color/white2"
        android:elevation="10dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/camera"
                android:layout_width="40dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="10dp"
                android:padding="5dp"
                app:srcCompat="@drawable/camera"
                android:contentDescription="TODO" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_weight="1"
                android:fontFamily="@font/bilbo_swash_caps"
                android:gravity="center|center_vertical"
                android:padding="5dp"
                android:text="Instagram"
                android:textColor="#000000"
                android:textSize="25sp"
                android:textStyle="bold" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="10dp"
                android:contentDescription="TODO"
                android:padding="5dp"
                app:srcCompat="@drawable/igtv"
                app:tint="@color/textcolor" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginEnd="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="10dp"
                android:padding="5dp"
                app:srcCompat="@drawable/send" />

        </LinearLayout>


    </androidx.appcompat.widget.Toolbar>


    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:labelVisibilityMode="selected"
        app:menu="@menu/bottom_nav_menu" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/nav_view"
        android:layout_below="@+id/toolbar"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation">

    </androidx.fragment.app.FragmentContainerView>

</RelativeLayout>

错误:-

Caused by: java.lang.IllegalStateException: Activity com.example.instagramclone.MainActivity@6a5f3da does not have a NavController set on 2131362023

at com.example.instagramclone.MainActivity.onCreate(MainActivity.java:29)

【问题讨论】:

  • 请将nav_host_fragment.xml 和navigation_graph.xml 的代码贴出来供我们进一步审核。
  • 请注意,您在onNavigationItemSelected() 中的代码虽然与您的异常无关,但绝对会导致您出现问题 - 在使用导航时,您永远不应该使用FragmentTransaction。请参阅this answer 了解如何正确实施。

标签: java android android-fragments


【解决方案1】:

根据this issue,当您同时使用Navigation.findNavController()FragmentContainerView 并尝试在活动的onCreate() 方法中访问NavController 时,这是预期的。

Navigation.findNavController() 依赖于片段的视图在被调用时已经存在(这就是为什么它需要片段所在视图的 ID)。但是,当使用FragmentTransactionFragmentContainerView(使用FragmentTransactionNavHostFragment 添加到您的布局)时,Fragment 的视图尚未在活动的onCreate() 中创建。因此,findNavController() 没有要查找的视图,因此是您的错误。

根据the 4th comment on that issue,您可以直接从NavHostFragment 中检索NavController(虽然Fragment 的视图 尚未创建,但Fragment 本身已经创建):

BottomNavigationView navView = findViewById(R.id.nav_view);

NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
    .findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();

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

【讨论】:

    【解决方案2】:

    如果您使用导航控制器,则无需在代码中使用它

                HomeFragment homeFragment = new HomeFragment();
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.nav_host_fragment , homeFragment);
                transaction.commit();
    

    相反,考虑使用这个

    Navigation.findNavController(it).navigate(YOUR ACTION)
    

    并考虑检查此链接docutmentation 对于正确使用 navHost 的教程,请考虑观看此nav host documentation

    【讨论】:

    • 这是一个大问题,需要修复,但与抛出的实际异常无关(在任何此代码被触发之前发生)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2021-10-01
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    相关资源
    最近更新 更多