android-反应过来的时候2单击按钮 [英] android- react when 2 button clicked
问题描述
我想建立简单的记忆游戏。我用16按钮。
我知道如何具体当按钮被cliked反应,但我怎么能应对每个按钮点击检查是否匹配按钮的选择(不neccesrly现在)?
I want to build simple memory game. I used 16 button. I know how to react when specific button is cliked, but how can I react to each button click and check if the match button was selected (not neccesrly now)?
推荐答案
在XML中,使用相同的名称为您的的onClick
每个按钮
In xml, use the same name for your onClick
for each Button
<Button
android:id="@+id/btn1"
...
android:onClick="btnClick"/>
<Button
android:id="@+id/btn2"
...
android:onClick="btnClick"/>
而在你的java code确保该函数是公共的,有你在XML的的onClick
财产上述相同的名称,它需要一个查看
作为其唯一的参数。在查看
将是按钮
点击这样你就可以得到它的 ID
和开关
上,使用的if / else
不过还是要处理的。
And in your java code make sure that the function is public, has the same name you defined in your xml's onClick
property above, and that it takes a View
as its only parameter. The View
will be the Button
clicked so you can get its id
and switch
on that, use if/else
or however you want to handle that
public void btnClick(View v)
{
switch(v.getId()) // v is the btn that was clicked so this will give you its id
{
case (R.id.btn1): btn1 was clicked
... do stuff
要回答你的第一个问题,你可以使用标志的建议提前或计数器,如果计数器==说2,然后点击确实你需要什么。如果没有,那么你存储的价值是什么按钮
重新presents在第二次点击比较
To answer your first question, you can use a flag as suggested earlier or a counter and if the counter == say 2 then the click does whatever you need. If it doesn't then you store the value of what that Button
represents to compare in the second click
其他的方法是将它们设置在循环
,我假设你知道如何建立一个循环
所以我会记住这简短
the other way would be to set them in a for loop
, I assume you know how to set up a loop
so I will keep this short
for (int i=0; i<buttons.size(); i++)
{
...
button[i].setOnClickListener(ActivityName.this);
}
@Override
public void onClick(View v)
{
int id = v.getId();
}
请确保你实施 OnClickListener()
这篇关于android-反应过来的时候2单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!