2012-02-20 54 views
2

我正在嘗試創建一個按鈕,當它被按住時,它會爲其添加1或任何數字,直到該按鈕被釋放。我的目標是創建一個屏幕上的光標鍵控制器來移動按鈕/位圖。下面的代碼只在按下時才加1。如何讓它連續計數?繼續計數按鈕

感謝您幫助

package s.apps.kontroler; 

import android.app.Activity; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Handler; 
import android.util.Log; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 
import android.widget.Button; 
import android.widget.TextView; 

public class Test extends Activity implements OnTouchListener { 

    Button up; 
    TextView text; 
    int countup; 

    boolean isDown = false; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.test); 

     up = (Button) findViewById(R.id.button1); 
     text = (TextView) findViewById(R.id.textView1); 

     up.setOnTouchListener(this); 

    } 

    public boolean onTouch(View arg0, MotionEvent event) { 
     // TODO Auto-generated method stub 

     int i = event.getAction(); 

     if (i == MotionEvent.ACTION_DOWN) { 
      isDown = true; 

      if (isDown) { 
       countup++; 
       text.setText("Count is: " + countup); 
      } 

      else if (i == MotionEvent.ACTION_UP) { 
       isDown = false; 
      } 

     } 
     return true; 
    } 
} 

回答

5

這應做到:

private static final int INTERVAL=500; 

private Handler handler= new Handler(); 

private Runnable incrementRunnable = new Runnable() { 
    @Override 
    public void run() { 
     countup++; 
     text.setText("Count is: " + countup); 
     handler.postDelayed(this, INTERVAL); 
    } 
} 


public boolean onTouch(View arg0, MotionEvent event) { 
    int i = event.getAction(); 
    if (i == MotionEvent.ACTION_DOWN) { 
     incrementRunnable.run(); 
    } 
    else if (i == MotionEvent.ACTION_UP) { 
     handler.removeCallbacks(incrementRunnable); 
    } 
    return true; 
} 
+0

爲此,我得到錯誤「處理程序不能被解除」,如果我把Handler處理程序=新的處理程序();在兩個處理程序行前面,那麼即使當我放手時,它也會添加任何錯誤。我該如何解決這個問題? – Srcko7 2012-02-20 20:18:56

+0

對不起,Handler handler = new Handler();不知何故被切碎。 – 2012-02-20 22:09:34

+0

謝謝你:) – Srcko7 2012-02-21 09:04:13

2

怎麼樣,

Calendar c = Calendar.getInstance(); 
    int i = c.get(Calendar.SECOND); 
    While(//button is held) 
    {if(c.get(Calender.SECOND)>i) 
    i++;//addto variable} 
+0

嘿,soory不知道你是怎麼換貨設置此,我m仍然是新的Android和Java :) – Srcko7 2012-02-20 20:25:06