首页 > 解决方案 > android studio:我的应用程序在启动后立即崩溃

问题描述

img1当我img2onCreate(). 但是,我真的需要全局声明这些变量。有任何想法吗?

package com.example.ui;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;




public class MainActivity extends AppCompatActivity implements View.OnClickListener  {
    /*img1 and img2 veriables below*/
    ImageView img1 = findViewById(R.id.img1);
    ImageView img2 = findViewById(R.id.img2);
    @Override

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

        /*my problem is fixed when I declare those variables here, but I need them to be global*/
        img1.setOnClickListener(this);
        img2.setOnClickListener(this);

          }

    @Override
    public void onClick(View view) {
        int id = view.getId();

        switch(id){
            case R.id.img1:
                Toast.makeText(this, "img1", Toast.LENGTH_SHORT).show();
                break;
            case R.id.img2:
                Toast.makeText(this, "img2", Toast.LENGTH_SHORT).show();

        }
    }
}

标签: androidandroid-studio

解决方案


你不能在那里使用 findViewById,试试这个:

public class MainActivity extends AppCompatActivity implements 
View.OnClickListener  {
private ImageView img1;
private ImageView img2;
@Override

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

    img1 = findViewById(R.id.img1);
    img2 = findViewById(R.id.img2);
    
    img1.setOnClickListener(this);
    img2.setOnClickListener(this);

      }

@Override
public void onClick(View view) {
    int id = view.getId();

    switch(id){
        case R.id.img1:
            Toast.makeText(this, "img1", Toast.LENGTH_SHORT).show();
            break;
        case R.id.img2:
            Toast.makeText(this, "img2", Toast.LENGTH_SHORT).show();

    }
}

这是文档


推荐阅读