android - android studio:我的应用程序在启动后立即崩溃
问题描述
img1
当我img2
在onCreate()
. 但是,我真的需要全局声明这些变量。有任何想法吗?
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();
}
}
}
解决方案
你不能在那里使用 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();
}
}
推荐阅读
- php - 对类的每次修改都会导致错误“无法声明类,因为该名称已在使用中”
- android - 以编程方式弹出/卸载 USB
- c# - 如何在反序列化时丢弃具有特定值的 JSON 元素
- git - 使用 JGit 克隆 Git 存储库时如何修复“Packfile is truncated”错误
- java - 如何将作为参数从 html 文件传递到 java applet 程序中的矩形的颜色设置
- java - 覆盖油漆组件只能改变颜色
- jquery - 显示文本动画停止使用水平滚动
- go - 什么是 golang.org/x 命名空间?
- java - 检索使用拦截器进行 HTTP 调用的方法的名称
- javascript - 如何在 NodeJS 中将 CSV 对象更改为 JSON