【发布时间】:2013-02-12 08:30:43
【问题描述】:
我是 Android 新手,在互联网上找到了一些很好的教程,所以我尝试了一个简单的活动,其中包含 if-else 语句。我在尝试“正确与错误”提示/Toast:
Button page1 = (Button) findViewById(R.id.button2);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
if (iv1.equals(R.drawable.airplane1)) {
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane2)) {
Toast.makeText(getApplicationContext(), "Please put an answer",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane3)){
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
我不确定我的if-else 语句有什么问题,但根本不会提示。我尝试删除 (iv1.equals(R.drawable.airplane3)) 和 (iv1.equals(R.drawable.airplane2)) 然后它只显示错误的 Toast。我似乎无法正确提示我。
这是我的课程的完整代码:
public class MainActivity extends Activity {
private static final Random imagerandom = new Random();
private static final Integer[] Imagesnumber =
{ R.drawable.airplane1, R.drawable.airplane2, R.drawable.airplane3, };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Integer a = Imagesnumber[imagerandom.nextInt(Imagesnumber.length)];
final ImageView iv = (ImageView) findViewById(R.id.imageView1);
View nextButton = findViewById(R.id.button1);
nextButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View V) {
int resource = Imagesnumber[imagerandom.nextInt(Imagesnumber.length)];
iv.setImageResource(resource);
}
});
Button page1 = (Button) findViewById(R.id.button2);
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final ImageView iv1 = (ImageView) findViewById(R.id.imageView1);
if (iv1.equals(R.drawable.airplane1)) {
Toast.makeText(getApplicationContext(), "Correct",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane2)) {
Toast.makeText(getApplicationContext(), "Please put an answer",
Toast.LENGTH_SHORT).show();
} else if (iv1.equals(R.drawable.airplane3)){
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
【问题讨论】:
-
让我看看我对你的理解是否正确,你是想看看你
iv1中显示的图像是什么? -
是 i
m trying to see if the imaged displayed in iv1 is correct or wrong using the if else im 不太确定我的 if else 语句有什么问题 -
您缺少 else 条件。我的意思是不满足您指定的 3 个 if 的条件
-
问题是您正在尝试查看图像视图是否等于可绘制对象的 Id,这些东西永远不会相等,因为它们是不同的对象。您可能想寻找一种方法从图像视图中获取当前的可绘制对象,然后查看它等于什么。
-
您正在将整数与 ImageViews 进行比较。那是行不通的。 R.drawable.airplane1 本身不是图像,它是作为资源标识符服务的 int。
标签: android