【问题标题】:Keep executing a method while a button is pressed in android在android中按下按钮时继续执行方法
【发布时间】:2015-04-27 00:18:23
【问题描述】:

我正在用 android 制作一个简单的游戏,中间有一个由 4 个按钮控制的精灵,我希望分配给按钮的方法在按下时将精灵沿相应方向移动,我已经尝试过onCreate 方法中的 this:

//initialization stuff...                               
button1.setOnTouchListener(new OnTouchListener{
@Override public boolean onTouch(View v, MotionEvent event){
    if(event.getAction == MotionEvent.ACTION_DOWN)
        move_sprite();//for example
    return true;      
}});

但这仅在我按下按钮时有效。我希望在按下按钮时执行该方法,以及如何控制该方法的更新时间。

【问题讨论】:

    标签: android button


    【解决方案1】:
    boolean fingerDown = false;
    
    button1.setOnTouchListener(new OnTouchListener() {
    
        @Override public boolean onTouch(View v, MotionEvent event){
            if(event.getAction == MotionEvent.ACTION_DOWN){
                 fingerDown = true;
                 move_sprite();
            } else if ( event.getAction() == MotionEvent.ACTION_UP ){
                 fingerDown = false;
            } 
            return true;      
        }
    });
    
    public void move_sprite(){
        // in new thread, or handler,
           while(fingerDown){
              // do your thing
           }
    }
    

    【讨论】:

    • 在新线程中?,如何?,我不明白,我知道线程是什么,但我不知道如何在另一个线程中实现它。
    • 嗯,这完全超出了这个问题的范围。最重要的是,如果你不知道如何旋转线程并且你正在做 Android 工作,我建议你阅读一下以远离 ui 线程。 developer.android.com/guide/components/…
    猜你喜欢
    • 2016-11-29
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多