从内部类中访问

时间:2013-10-16 20:33:47

标签: android button android-activity main demo

我对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);
        }
    });
}

}

1 个答案:

答案 0 :(得分: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(最有可能使用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);