2013年8月4日 星期日

[Android] 如何監測長按結束 (Detect End of Long Press)

這個範例,我們來看看如何監看按壓按鈕的三個狀態
(This example will show you how to monitor click, long press and release button status)
1)點擊(click)
2)長按(long press)
3)放開(release)

File : MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class MainActivity extends Activity {

 boolean isBtnLongPressed = false;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  Button btn = (Button) findViewById(R.id.button1);

  btn.setOnLongClickListener(new HoldListener());
  btn.setOnTouchListener(new touchListener());
  btn.setOnClickListener(new clickListener());
 }

 //監聽點擊(detect click)
 private class clickListener implements OnClickListener {

  @Override
  public void onClick(View view) {
   Log.e("log", "click button");
  }
 }

 //監聽長按(detect long press)
 private class HoldListener implements OnLongClickListener {

  @Override
  public boolean onLongClick(View pView) {
   // Do something when your hold starts here.
   isBtnLongPressed = true;
   Log.e("log", "long press button");
   return true;
  }

 }

 //監聽放開按鈕(detect release button)
 private class touchListener implements OnTouchListener {

  @Override
  public boolean onTouch(View pView, MotionEvent pEvent) {
   
   if (pEvent.getAction() == MotionEvent.ACTION_UP) {
    
    if (isBtnLongPressed) {
     // Do something when the button is released.
     isBtnLongPressed = false;
     Log.e("log", "release");
    }
   }
   return false;
  }
 }

}


沒有留言:

張貼留言