我在 onClick()
方法之外有一个 arrayList。我指的是我的 onClick()
类中 arrayList 中的一些元素。但是当我输入 ArrayList 和列表的名称时,它会以红色突出显示。不过,这两个类(class)都是公开的。
我尝试过放置 arryalist 的代码和列表随机化过程,但是每次我单击某些内容时它都会重新随机化。
给我带来错误的部分是 switch case 语句中的第一种情况,我尝试获取 allImages 数组列表中的第一个位置以及 imageList 列表中的第一个位置。它们属于 onclick 类。 arrayList 和 List 不属于该类。
我无法将 arrayList 和 List 放入类中,因为每次我单击某些内容时,它们都会重新随机化。 (我正在尝试做一个配对游戏)
这是代码:
public void Random() {
Integer[] allImages = { R.drawable.cheetah, R.drawable.cheetah, R.drawable.chick, R.drawable.chick, R.drawable.fox,
R.drawable.fox, R.drawable.giraffe, R.drawable.giraffe, R.drawable.owl,
R.drawable.owl, R.drawable.panda, R.drawable.panda, R.drawable.sheep, R.drawable.sheep, R.drawable.tiger,
R.drawable.tiger};
List<Integer> imageList = Arrays.asList(allImages);
Collections.shuffle(imageList);
imageList.toArray(allImages);
}
public void onClick(View v) {
final int id = v.getId();
if (maxCounter < 2) {
switch (id) {
case R.id.one:
one.setBackgroundResource(allImages[0]); THE ALL IMAGES PART HIGHLIGHTS IN RED
unmatchedImages[maxCounter] = R.id.one;
unmatchedImages[maxCounter++] = imageList.get(0); ALSO IMAGE LIST HIGHLIGHTS IN RED
break;
//After this, i have cases for each button
}
}
else {
one.setBackgroundResource(R.drawable.qmarks);
//After this, i have a setBackgroundResource for each button
}
}
请帮忙。任何帮助是极大的赞赏。
最佳答案
你的Random()
应该是方法还是类?
基于名称,从大写字母(Random
)开始,它看起来像类。
但是您在名称之前添加了 public void
,因此它是方法。
我认为您可以将您的 Random()
方法 (!) 内容移动到您的 Activity
中。您打算在 Fragment
或 Activity
中设置吗?
要做的步骤:
1)将您的列表移动为 Activity 中的字段(或 fragment - 我不知道您有什么)
2) 在 onCreate()
中随机播放列表(或者在不同的地方,但在第一次使用之前)
// 0 - Use it in your class.
// This "MainActivity" is only for example - use your name!
public class MainActivity extends AppCompatActivity {
// 1 - List of items
List<Integer> allImages = {R.drawable.cheetah, R.drawable.cheetah, R.drawable.chick,
R.drawable.chick, R.drawable.fox, R.drawable.fox, R.drawable.giraffe,
R.drawable.giraffe, R.drawable.owl, R.drawable.owl, R.drawable.panda,
R.drawable.panda, R.drawable.sheep, R.drawable.sheep, R.drawable.tiger,
R.drawable.tiger};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 2 - Shuffle them
Collections.shuffle(imageList);
}
.
.
.
}
关于java - 我在 onClick 方法之外有一个引用 arrayList 的 arrayList,但它给了我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61180367/