0

我对 Android 编程很陌生,有一点问题。

错误是:

Variable 'Demo_Button' is accessed from within inner class. Needs to declared final.

我尝试了什么:

改为Demo_button.setImageResource(R.drawable.pressed);_final Demo_button.setImageResource(R.drawable.pressed);

package com.iklikla.eightgame;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ImageButton Demo_button = (ImageButton)findViewById(R.id.imageButton);

    Demo_button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Demo_button.setImageResource(R.drawable.pressed);
        }
    });
}

}
4

1 回答 1

1

这里有几个选择

首先,我将其声明为成员变量,然后它将起作用

public class MainActivity extends Activity {

    ImageButton Demo_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Demo_button = (ImageButton)findViewById(R.id.imageButton);

其次,由于您正在更改View被点击的内容,您可以通过这种方式访问​​它

emo_button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

    ImageButton btn = (ImageButton)v; // cast the View to an ImageButton
        btn.setImageResource(R.drawable.pressed);
    }
});

不相关,但会在当前代码的运行时给您一个错误,您需要layout在尝试初始化之前充气 a Button(很可能使用setContentView())。所以使用我的第一个例子它看起来像

public class MainActivity extends Activity {

    ImageButton Demo_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.my_layout);  // where my_layout is the name of your layout
                                             // file containing the Button without the xml extension
       Demo_button = (ImageButton)findViewById(R.id.imageButton);
于 2013-10-16T20:36:39.893 回答