【问题标题】:Accessed from within inner Class从内部类中访问
【发布时间】:2013-10-25 03:36:52
【问题描述】:

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

}

【问题讨论】:

  • 不是问题的一部分,但在 java 中变量名通常以小写字母开头并且没有下划线。例如demoButton

标签: android button android-activity main demo


【解决方案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);
    }
});

不相关,但会在运行时使用当前代码给您一个错误,您需要在尝试初始化 Button 之前填充 layout(很可能使用 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);

【讨论】:

  • 非常感谢..现在没有错误..但应用程序不断崩溃..代码:pastebin.com/ETd1qtMJ
  • 是的,那是因为你没有注意我回答的最后一部分。我说如果你在尝试初始化View之前没有添加setContentView(),就会发生这种情况
  • "...我如何在触摸后停用它"你是什么意思?你想“停用”什么,“停用”是什么意思?
  • 我希望 ImageButton 显示另一个图像,同时将手指放在上面。释放后,它应该会恢复正常..
  • 最好的方法是创建一个选择器文件并使用StateListDrawables。按住按钮时使用android:state_pressed 获取所需的图像
猜你喜欢
  • 2021-04-27
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 2011-01-02
  • 2017-08-18
相关资源
最近更新 更多