机器人:ImageView的和ButtonView误差对象声明
问题描述:
我在哪里能声明的ImageView和ButtonView对象的一个问题:机器人:ImageView的和ButtonView误差对象声明
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_partita);
}
public int cont = 0;
int sceltaG1 = 0;
int sceltaPc = 0;
ImageButton G1 = (ImageButton) findViewById(R.id.g1view);
ImageView Pc = (ImageView) findViewById(R.id.pcview);
ImageButton VS = (ImageButton) findViewById(R.id.vsview);
public void giocoG1()
{
if (sceltaG1==0) G1.setImageResource(R.drawable.sasso_logo);
if (sceltaG1==1) G1.setImageResource(R.drawable.carta_logo);
if (sceltaG1==2) G1.setImageResource(R.drawable.forbici_logo);
}
public void giocoPc()
{
sceltaPc = (int) (Math.random()*3);
if (sceltaPc==0) Pc.setImageResource(R.drawable.sasso_logo);
if (sceltaPc==1) Pc.setImageResource(R.drawable.carta_logo);
if (sceltaPc==2) Pc.setImageResource(R.drawable.forbici_logo);
}
public void cambioScelta()
{
if (sceltaG1==2) sceltaG1 = 0;
else sceltaG1++;
giocoG1();
}
giocoG1(),giocoPc()和sceltaGicoO()是3个按钮的onClick我没有问题。
但是,当我启动应用程序(没有语法错误),我走在这种活力,应用程序做一个“坏的关闭”。我发现这个问题是这些对象声明:
ImageButton G1 = (ImageButton) findViewById(R.id.g1view);
ImageView Pc = (ImageView) findViewById(R.id.pcview);
ImageButton VS = (ImageButton) findViewById(R.id.vsview);
我试图将它们插入在OnCreate funnction,他们不给的问题,但功能下看不到物体。 我该如何解决?谢谢
答
您需要在任何方法之外声明对象引用,并在onCreate()
方法中初始化它们。
private ImageButton G1;
private ImageView Pc;
private ImageButton VS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_partita);
G1 = (ImageButton) findViewById(R.id.g1view);
Pc = (ImageView) findViewById(R.id.pcview);
VS = (ImageButton) findViewById(R.id.vsview);
}
答
你定义ImageButtons和ImageView的正下方您的INT-变中,但不分配一个值。然后,在onCreate()你必须做findViewById。
干杯