尝试引用最终的 ImageView 不起作用

Trying to refer to a final ImageView does not work

我的问题是我无法从其他方法引用我的最终 imageView(在 onCreate 中创建)。 我想要做的是将图片路径保存在一个数组中,并使用 onTouchListener 更改 imageView 的图片。 我收到错误 "imageView cannot be resolved"。我尝试了很多东西,但没有任何效果。我可以在 R 和 xml.

中找到我的 imageView

我尝试在新方法 nextCard() 中使用我的 imageView:

public void nextCard() {
  rdmGenerated = randomZahl(0, 52);     
  rdmConverted = (int)rdmGenerated;
  imageView.setImageResource(card[rdmConverted]);
}

我的 onCreate 看起来像这样:

protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ImageView imageView = (ImageView)findViewById(R.id.imageView);

        imageView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                nextCard();
            }
        });
}

我的卡片阵列是这样的:

有什么问题吗?我检查了区分大小写并且已经清理并构建了 hundret 时间。也许它与方法声明有关(public void wrong for using final variables?)

提前致谢

几天前我遇到了同样的问题。我所做的是,我将变量设为静态,以便能够将它引用到我希望用来访问该变量的所有方法。例如:如果假设我想访问 ImageView,我声明为:

private static ImageView imageView;

然后在 onCreate 中它被初始化,希望它应该对所有其他方法可用.. 并且此声明将在 activity 本身的 onCreate 之前完成(如果您想知道在哪里声明)希望对您有所帮助。

您已经在 onCreate 方法中声明了 imageView,因此它只有局部作用域。尝试将 imageView 声明为 class 成员。

懒伪

Class 东西

私有ImageView imageView;

oncreate() 方法
imageView = (ImageView)findViewById(R.id.imageView);