我想从editText获得用户输入,并检查它是否等于随机数组图像。我如何获取用户的输入,并查看它是否与显示的图像匹配?
这是我用来从阵列中获得随机图像的代码:
images[rand.nextInt(images.length)]
这是我的代码:
public void enterButton(View view) {
String imageTitle = ImageDrawable.getTitle();
String guess = userGuess.getText().toString();
if (imageTitle == guess) {
Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Try Again!",
Toast.LENGTH_SHORT).show();
}
}
Drawables[] drawables = ...;
String[] titles = ...;
ImageDrawable[] imageDrawables = new ImageDrawable[drawables.length];
if (drawables.length != titles.length) {
throw ...;
}
for (int i=0;i<drawables.length;i++) {
imageDrawables[i] = new ImageDrawable(drawable, titles[i]);
}
根据PO在问题评论中给出的详细解释,这是我的建议:
基本上,我们有一个图像中有一些东西(例如猫(,用户需要插入他的猜测,说出图像中的内容。无论用户是对是错,应用程序都应该显示一条反馈消息。
我建议对基于对象imageDrawable
的代码进行此编辑。该对象将包含一个字段imageTitle
,该字段将与用户的猜测进行比较。
imageDrawable
对象应该是您创建的对象。它可以封装基本的Drawable
,也可以是一个具有实际Drawable
资源路径的全新对象。我认为使用自定义对象将是最清晰的编写方式,而且它还可以轻松控制图像标题。
public void enterButton(View view) {
String imageTitle = imageDrawable.getTitle(); // TODO: implement imageDrawable with ImageDrawable class and initialize it
String guess = userGuess.getText().toString();
if (imageTitle == guess)) {
Toast.makeText(this, "Correct!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Try Again!", Toast.LENGTH_SHORT).show();
}
}
例如,如果我们有一个Drawables
数组,我们可以将其转换为ImageDrawables
数组,也可以使用图像标题,然后使用该数组。(您仍然应该实现ImageDrawable
类(。
Drawables[] drawables = ...;
String[] titles = ...;
ImageDrawable[] imageDrawables = new ImageDrawable[drawables.length];
if (drawables.length != titles.length) {
throw ...;
}
for (int i=0;i<drawables.length;i++) {
imageDrawables[i] = new ImageDrawable(drawable, titles[i]);
}
然后使用imageDrawables
。