首页 > 解决方案 > 当我使用 findfindViewById 定义两个浮动按钮时,为什么我的应用程序会崩溃?

问题描述

当我尝试通过设置 2 个按钮时findViewById(..)。但是,我的应用程序崩溃了。

我已经对其进行了搜索并修复了代码中的一些错误,但即便如此,应用程序仍然崩溃,我不知道原因。

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.i(TAG,"called onCreate");
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    less_button= findViewById(R.id.lessButton);
    plus_button = findViewById(R.id.plusButton);
    setContentView(R.layout.activity_main);


    if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
            == PackageManager.PERMISSION_DENIED){
        ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, 100);
    }

    mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.opencv_camera_activity_surface_view);
    mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
    mOpenCvCameraView.setCvCameraViewListener(this);

    flash = findViewById(R.id.fabFlashLight);

    flash.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(((JavaCameraView) mOpenCvCameraView).isFlashModeOn()){

                ((JavaCameraView) mOpenCvCameraView).turnOffTheFlash();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    flash.setImageDrawable(getDrawable(R.drawable.ic_twotone_flash_off_24px));
                }

            }
            else{
                ((JavaCameraView) mOpenCvCameraView).turnOnTheFlash();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    flash.setImageDrawable(getDrawable(R.drawable.ic_twotone_flash_on_24px));
                }
            }
        }
    });

    zoom = findViewById(R.id.seekBar);

    zoom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            ((JavaCameraView) mOpenCvCameraView).setSeekBarZoom(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            seekBar.setProgress(((JavaCameraView) mOpenCvCameraView).getSeekBarZoom());
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });


    first = findViewById(R.id.floatingActionButton);
    second = findViewById(R.id.floatingActionButton2);
    third = findViewById(R.id.floatingActionButton3);
    first.hide();
    second.hide();
    third.hide();


    mFirstButton = findViewById(R.id.firstButton);
    mSecondButton = findViewById(R.id.secondButton);
    mThirdButton = findViewById(R.id.thirdButton);
    mFirstButton.setVisibility(View.INVISIBLE);
    mSecondButton.setVisibility(View.INVISIBLE);
    mThirdButton.setVisibility(View.INVISIBLE);

    res = findViewById(R.id.textView);
    res.setText("");

    try {
        mPhotoFile = createImageFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

这是我得到的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.maxwellar, PID: 24791
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.maxwellar/com.example.maxwellar.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3042)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3282)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1970)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7156)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
        at android.support.v7.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
        at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
        at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
        at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
        at com.example.maxwellar.MainActivity.<init>(MainActivity.java:96)
        at java.lang.Class.newInstance(Native Method)
        at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
        at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1219)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3030)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3282) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1970) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7156) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)

标签: android

解决方案


您需要先使用setContentView(R.layout.activity_main),然后才能使用 findViewById(...) 而不会出错。正如您在文档中看到的那样,setContentView 负责:

从布局资源设置活动内容。资源将被膨胀,将所有顶级视图添加到活动中。

因此,如果不调用setContentView活动,则不知道应该在哪里查找(在您的情况下)按钮 ID。


推荐阅读