IllegalArgumentException:ID 未引用此 Activity 内的视图

问题描述 投票:0回答:4

我一直在尝试为我的应用程序制作一个主页,其中包含一些现代仪表板和导航抽屉。 在我的代码中发现错误:

 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.thinkerlab, PID: 13956
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.thinkerlab/com.example.thinkerlab.HomePage}: java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2517)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2577)
        at android.app.ActivityThread.access$1000(ActivityThread.java:166)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1414)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5619)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:853)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:737)
     Caused by: java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
        at androidx.core.app.ActivityCompat.requireViewById(ActivityCompat.java:368)
        at androidx.navigation.Navigation.findNavController(Navigation.java:58)
        at com.example.thinkerlab.HomePage.onCreate(HomePage.java:70)
        at android.app.Activity.performCreate(Activity.java:6351)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1114)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2470)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2577) 
        at android.app.ActivityThread.access$1000(ActivityThread.java:166) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1414) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:5619) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:853) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:737) 

我的项目的AndroidManifest.xml文件:

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Page1"></activity>
    <activity android:name=".Startpage" />
    <activity
        android:name=".HomePage"
        android:label="@string/title_activity_home_page"
        android:theme="@style/AppTheme.NoActionBar" />
    <activity android:name=".ResetPassword" />
    <activity android:name=".RegistrationActivity" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="preloaded_fonts"
        android:resource="@array/preloaded_fonts" />
</application>

我的项目的HomePage.java文件:

 package com.example.thinkerlab;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.Menu;
import android.widget.Toast;

import com.google.android.material.navigation.NavigationView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class HomePage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    DrawerLayout drawerLayout;
    NavigationView navigationView;
    Toolbar toolbar;
    ActionBar actionBar;
    Activity activity;

    private AppBarConfiguration mAppBarConfiguration;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        toolbar = findViewById(R.id.toolbar2);
        setSupportActionBar(toolbar);

       actionBar = getSupportActionBar();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        getSupportActionBar().setHomeButtonEnabled(true);

        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);

        Menu menu=navigationView.getMenu();
        menu.findItem(R.id.nav_Log_out).setVisible(true);
        menu.findItem(R.id.nav_Profile).setVisible(true);
        navigationView.bringToFront();

        ActionBarDrawerToggle toggle= new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);
        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_gallery, R.id.nav_slideshow)
                .setDrawerLayout(drawerLayout)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }




    public void onBackPressed()
    {
        if(drawerLayout.isDrawerOpen(GravityCompat.START))
        {
            drawerLayout.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.home_page, menu);
        return true;
    }



    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }


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

        switch (item.getItemId())
        {
            case R.id.nav_home:
                break;
            case R.id.nav_Science:
                startActivity(new Intent(HomePage.this,Page1.class));
                break;
            case R.id.nav_Contact_Us:
                Toast.makeText(this,"Share",Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_Log_out:
                startActivity(new Intent(HomePage.this,MainActivity.class));
                break;

        }
        drawerLayout.closeDrawer(GravityCompat.START);
        return  true;
    }
}

我的项目的styles.xml文件:

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>


</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

我的activity_home_page 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:openDrawer="start">
    <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/header"
        app:menu="@menu/main_menu" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">



        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">


            <ImageView
                android:id="@+id/iv1"
                android:layout_width="0dp"
                android:layout_height="150dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/textView2"
                app:layout_constraintTop_toBottomOf="@+id/toolbar2"
                app:srcCompat="@drawable/p" />

            <TextView
                android:id="@+id/textView3"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:fontFamily="sans-serif-condensed-medium"
                android:text="Let's Think and Build"
                android:textSize="18sp"
                app:layout_constraintEnd_toStartOf="@+id/iv1"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView2" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:fontFamily="serif"
                android:text="Thinker Lab"
                android:textSize="36sp"
                app:layout_constraintEnd_toStartOf="@+id/iv1"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/toolbar2" />
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar2"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:background="#04FFFFFF"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"


                android:minHeight="?attr/actionBarSize"
                android:theme="?attr/actionBarTheme"
                tools:layout_editor_absoluteX="1dp"
                tools:ignore="MissingConstraints" />


            <LinearLayout
                android:id="@+id/linearLayout2"
                android:layout_width="0dp"
                android:layout_height="175dp"
                android:orientation="horizontal"
                android:padding="10dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/iv1">

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp"
                    android:layout_weight="1">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <ImageView
                            android:id="@+id/iv2"
                            android:layout_width="75dp"
                            android:layout_height="75dp"
                            android:layout_centerHorizontal="true"
                            android:layout_marginTop="15dp"
                            app:srcCompat="@drawable/science" />

                        <TextView
                            android:id="@+id/textView4"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@id/iv2"
                            android:layout_centerHorizontal="true"
                            android:layout_marginTop="10dp"
                            android:fontFamily="@font/aclonica"
                            android:text="Science"
                            android:textSize="18sp" />
                    </RelativeLayout>
                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp"
                    android:layout_weight="1">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <ImageView
                            android:id="@+id/iv3"
                            android:layout_width="75dp"
                            android:layout_height="75dp"
                            android:layout_centerHorizontal="true"
                            android:layout_marginTop="15dp"
                            app:srcCompat="@drawable/maths" />

                        <TextView
                            android:id="@+id/textView5"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@id/iv3"
                            android:layout_centerHorizontal="true"
                            android:layout_marginTop="10dp"
                            android:fontFamily="@font/aclonica"
                            android:text="Mathematics"
                            android:textSize="18sp" />
                    </RelativeLayout>
                </androidx.cardview.widget.CardView>
            </LinearLayout>

            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="175dp"
                android:orientation="horizontal"
                android:padding="10dp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintHorizontal_bias="0.0"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/linearLayout2">

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp"
                    android:layout_weight="1">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <ImageView
                            android:id="@+id/iv4"
                            android:layout_width="75dp"
                            android:layout_height="75dp"
                            android:layout_centerHorizontal="true"
                            android:layout_marginTop="15dp"
                            app:srcCompat="@drawable/engg" />

                        <TextView
                            android:id="@+id/textView6"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@id/iv4"
                            android:layout_centerHorizontal="true"
                            android:layout_marginTop="10dp"
                            android:fontFamily="@font/aclonica"
                            android:text="Engineering"
                            android:textSize="18sp" />
                    </RelativeLayout>
                </androidx.cardview.widget.CardView>

                <androidx.cardview.widget.CardView
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_margin="10dp"
                    android:layout_weight="1">

                    <RelativeLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent">

                        <ImageView
                            android:id="@+id/iv5"
                            android:layout_width="75dp"
                            android:layout_height="75dp"
                            android:layout_centerHorizontal="true"
                            android:layout_marginTop="15dp"
                            app:srcCompat="@drawable/tech" />

                        <TextView
                            android:id="@+id/textView7"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_below="@id/iv5"
                            android:layout_centerHorizontal="true"
                            android:layout_marginTop="10dp"
                            android:fontFamily="@font/aclonica"
                            android:text="Technology"
                            android:textSize="18sp" />
                    </RelativeLayout>
                </androidx.cardview.widget.CardView>
            </LinearLayout>
        </androidx.constraintlayout.widget.ConstraintLayout>
    </ScrollView>

</androidx.drawerlayout.widget.DrawerLayout>

请帮我找到解决方案。我已经被困在这个问题上一个多星期了。

android-studio nullpointerexception android-actionbar illegalargumentexception
4个回答
6
投票

您正在使用此导航控制器

 mNavController = findNavController(R.id.nav_host_fragment_activity_main)

你需要使用这个 supportFragmentManager 导航控制器

    val navHostFragment =
   supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) 
    as NavHostFragment
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    mNavController = navHostFragment.navController

xml 代码如下

    <androidx.fragment.app.FragmentContainerView
    android:id="@+id/nav_host_fragment_activity_main"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    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" />

5
投票

我在使用多模块开发时也遇到了这个问题。经过调查,我发现这是因为我在另一个模块中创建了同名的XML。那个XML里没有,改个名字就解决了。


0
投票

这都是关于文件命名的。回想一下您最近添加/替换/重命名的文件并将其回滚。


0
投票

将 FragmentContainer Id 传递给 findNavController 方法... 或者 选择与 NavHost 的 id 相同的 FragmentContaier 的 id...

这个改变的ID。解决了我的问题!

© www.soinside.com 2019 - 2024. All rights reserved.