首先,您必須知道,每次調用findViewById()都會浪費應用程序的大量時間,因此您最好讓它們使用一次並多次使用它們。
Android - Hold Button to Repeat Action
我複製的代碼爲您輕鬆:
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
/**
* A class, that can be used as a TouchListener on any view (e.g. a Button).
* It cyclically runs a clickListener, emulating keyboard-like behaviour. First
* click is fired immediately, next one after the initialInterval, and subsequent
* ones after the normalInterval.
*
* <p>Interval is scheduled after the onClick completes, so it has to run fast.
* If it runs slow, it does not generate skipped onClicks. Can be rewritten to
* achieve this.
*/
public class RepeatListener implements OnTouchListener {
private Handler handler = new Handler();
private int initialInterval;
private final int normalInterval;
private final OnClickListener clickListener;
private Runnable handlerRunnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(this, normalInterval);
clickListener.onClick(downView);
}
};
private View downView;
/**
* @param initialInterval The interval after first click event
* @param normalInterval The interval after second and subsequent click
* events
* @param clickListener The OnClickListener, that will be called
* periodically
*/
public RepeatListener(int initialInterval, int normalInterval,
OnClickListener clickListener) {
if (clickListener == null)
throw new IllegalArgumentException("null runnable");
if (initialInterval < 0 || normalInterval < 0)
throw new IllegalArgumentException("negative interval");
this.initialInterval = initialInterval;
this.normalInterval = normalInterval;
this.clickListener = clickListener;
}
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.removeCallbacks(handlerRunnable);
handler.postDelayed(handlerRunnable, initialInterval);
downView = view;
downView.setPressed(true);
clickListener.onClick(view);
return true;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handler.removeCallbacks(handlerRunnable);
downView.setPressed(false);
downView = null;
return true;
}
return false;
}
}
而按鈕抱着你必須使用下面的鏈接,並使用自定義監聽器此鏈接提供了重複的代碼然後在你的onCreate()中像下面一樣使用它:
View player1 = findViewById(R.id.player1);
View player2 = findViewById(R.id.player2);
button.setOnTouchListener(new RepeatListener(400, 100, new OnClickListener() {
@Override
public void onClick(View view) {
// the code to execute repeatedly
player1.setX(player1.getX() - 30);
player2.setX(player2.getX() + 30);
}
}));
爲了更好的代碼,你可以定義player1和player2 public(out of your onCreate),然後在onCreate()啓動它們()
感謝您的幫助,但是當我嘗試使用代碼運行項目時,出現setOnTouchListener說「int不能被解除引用」。我已經嘗試導入android.view.View.OnTouchListener,並沒有解決它。你知道爲什麼會出現這個錯誤嗎? – HF1
將錯誤日誌完全添加到您的問題 –
onclick中存在您的代碼錯誤。告訴我你剛剛添加到你的代碼中。 –