안드로이드 개발 질문/답변
(글 수 45,052)
<Button
android:id="@+id/btn_plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Plus"
/>
<Button
android:id="@+id/btn_minus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Minus"
/>
위 두 버튼으로 값을 증가 또는 감소 시키는 일을 하는데
클릭 할때마다 +1을 하거나 -1을 하는건 어려운게아닌데
100씩 이렇게 크게 값을 증가 시키기가 넘 무식하니깐
누르고 있으면 자동으로 증가 시키게 만들고 싶은데 이런건 어떤 이벤트를 잡아서 처리하나요?
setOnClickListener 은 한번씩 눌러줘야되서 귀찮은데요 방법 좀...
2012.01.12 16:00:43
package com.yourdomain.yourlibrary;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
public class AutoRepeatButton extends Button {
private long initialRepeatDelay = 500;
private long repeatIntervalInMilliseconds = 100;
private Runnable repeatClickWhileButtonHeldRunnable = new Runnable() {
@Override
public void run() {
//Perform the present repetition of the click action provided by the user
// in setOnClickListener().
performClick();
//Schedule the next repetitions of the click action, using a faster repeat
// interval than the initial repeat delay interval.
postDelayed(repeatClickWhileButtonHeldRunnable, repeatIntervalInMilliseconds);
}
};
private void commonConstructorCode() {
this.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN)
{
//Just to be sure that we removed all callbacks,
// which should have occurred in the ACTION_UP
removeCallbacks(repeatClickWhileButtonHeldRunnable);
//Perform the default click action.
performClick();
//Schedule the start of repetitions after a one half second delay.
postDelayed(repeatClickWhileButtonHeldRunnable, initialRepeatDelay);
}
else if(action == MotionEvent.ACTION_UP) {
//Cancel any repetition in progress.
removeCallbacks(repeatClickWhileButtonHeldRunnable);
}
//Returning true here prevents performClick() from getting called
// in the usual manner, which would be redundant, given that we are
// already calling it above.
return true;
}
});
}
public AutoRepeatButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
commonConstructorCode();
}
public AutoRepeatButton(Context context, AttributeSet attrs) {
super(context, attrs);
commonConstructorCode();
}
public AutoRepeatButton(Context context) {
super(context);
commonConstructorCode();
}
}
다음 예제를 참조하십시오.
누르고 있으면 onClick을 계속 발생시키는 버튼 클래스입니다.package 줄만 고치면큰 수정없이 버튼처럼 사용할 수 있습니다.
출처는 stackoverflow.com 입니다.




터치리스너 쓰시면됩니다 ㅎㅎ