You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android闪屏页开发报错求助:Attempt to invoke virtual method 'android.view.View android.widget.ImageView.findViewById(int)' on a null object reference

解决闪屏页的NullPointerException问题

Hey there, that null pointer error you're seeing is a super common mistake—let's get it fixed right away!

问题根源

你当前的代码里,SplashImg 和 SplashText 这两个控件变量只是声明了,但没有初始化赋值。你错误地调用了 SplashImg.findViewById(R.id.iv_splash),这相当于在一个null对象上调用方法,自然会抛出 Attempt to invoke virtual method... on a null object reference 错误。

正确的做法是调用Activity的findViewById()方法,从你设置的布局中找到对应的控件,然后赋值给这两个变量。

修正后的SplashScreenActivity.java代码

package com.anurag.college_information;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class SplashScreenActivity extends AppCompatActivity {
    ImageView SplashImg;
    TextView SplashText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash_screen);
        
        // 修正:调用Activity的findViewById获取控件并赋值
        SplashImg = findViewById(R.id.iv_splash);
        SplashText = findViewById(R.id.tv_splash);

        SplashImg.animate().translationY(-1600).setDuration(1000).setStartDelay(1000);
        SplashText.animate().translationY(1600).setDuration(1000).setStartDelay(1000);

        // 优化:指定主线程Looper,适配Android 11+
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);
                finish();
            }
        }, 3000);
    }
}

额外小提示

  1. 如果你使用的是Android Studio Arctic Fox及以上版本,推荐使用**视图绑定(View Binding)**来替代findViewById,它可以完全避免这类空指针问题,代码也更简洁。
  2. 你的布局文件activity_splash_screen.xml本身没有问题,不需要修改。

内容的提问来源于stack exchange,提问作者AnuragK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 02:42:32