本文介绍了如何在 Android onClick 函数中设置延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

)我正在创建一个记忆游戏.我的问题是,每当我第二次点击时,我什至看不到切换按钮.要清楚 - 第一次单击切换切换按钮,所以我可以看到它持有的数字,第二次单击不同的切换按钮应该切换它,显示数字,然后继续设置分数 +1,如果数字是相同,或者如果它们不同,则再次反转它们.

)I'm in a process of creating a memory game. My problem is that whenever i click for the second time, i can't even see toggled button. To be clear - first click toggles the togglebutton, so i can see the number it holds, the second click on a different togglebutton is suposed to toggle it, show me the number and then proceed to either set a score +1 if numbers are the same, or reverse them back again if they're different.

下面是我用作 onClick 函数的代码,我一直在考虑在第二个if 块"中放置某种睡眠或延迟函数 - (if(klikniecia ==2)).

Below is the code that i use as my onClick function, i've been thinking about putting some kind of sleep or delay function somwhere in the second "if block" - (if(klikniecia ==2)).

任何有关此主题的帮助将不胜感激.

Any help on this topic would be appreciated.

public void onClick(View view) {
for (int i = 0; i < karta.length; i++){
    if (view == karta[i]){
        karta[i].setEnabled(false);
        klikniecia++;
        if (klikniecia == 1){
            kartaID[0]=i;
            kartaWartosc[0]=listaKart.get(i);

        }
        if (klikniecia == 2){
            kartaID[1]=i;
            kartaWartosc[1]=listaKart.get(i);

            //i think, about setting a delay here, so i can see both of the cards, regardles if the're the same or not before reverting them.

            if (czyPara()){
                karta[kartaID[0]].setEnabled(false);
                karta[kartaID[1]].setEnabled(false);
                klikniecia=0;
            }
            else{

                karta[kartaID[0]].setEnabled(true);
                karta[kartaID[0]].toggle();
                karta[kartaID[1]].setEnabled(true);
                karta[kartaID[1]].toggle();
                klikniecia=0;

            }
        }

    }

}

}

推荐答案

您可以将延迟消息发布到处理程序(带有关联的可运行对象)并让它更新 UI,而不是在 onclick 中休眠.显然将其融入您的应用设计并使其工作,但基本思想是这样的:

Instead of sleeping in the onclick, you could post a delayed message to a handler (with associated runnable) and have it update the UI. Obviously fit this into the design of your app and make it work, but the basic idea is this:

//Here's a runnable/handler combo
private Runnable mMyRunnable = new Runnable()
{
    @Override
    public void run()
    {
       //Change state here
    }
 };

然后从 onClick 将延迟消息发布到处理程序,指定要执行的可运行对象.

Then from onClick you post a delayed message to a handler, specifying that runnable to be executed.

Handler myHandler = new Handler();
myHandler.postDelayed(mMyRunnable, 1000);//Message will be delivered in 1 second.

根据您的游戏的复杂程度,这可能不是您想要的,但它应该让您有一个开始.

Depending on how complicated your game is, this might not be exactly what you want, but it should give you a start.

这篇关于如何在 Android onClick 函数中设置延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-21 00:24