android自訂view的長按事件的執行時間

來源:互聯網
上載者:User
package com.example.longpress;/**  * @author 作者 E-mail: chenshaohua2012@126.com * @version 建立時間:2013-1-15 下午12:07:32  * 類說明  */import android.content.Context;import android.view.MotionEvent;import android.view.View;public class LongPressView1 extends View {private int mLastMotionX, mLastMotionY;// 是否移動了private boolean isMoved;// 是否釋放了private boolean isReleased;// 計數器,防止多次點擊導致最後一次形成longpress的時間變短private int mCounter;// 長按的runnableprivate Runnable mLongPressRunnable;// 移動的閾值private static final int TOUCH_SLOP = 20;public LongPressView1(Context context) {super(context);mLongPressRunnable = new Runnable() {@Overridepublic void run() {System.out.println("thread");System.out.println("mCounter--->>>"+mCounter);System.out.println("isReleased--->>>"+isReleased);System.out.println("isMoved--->>>"+isMoved);mCounter--;// 計數器大於0,說明當前執行的Runnable不是最後一次down產生的。if (mCounter > 0 || isReleased || isMoved)return;performLongClick();// 回調長按事件}};}public boolean dispatchTouchEvent(MotionEvent event) {int x = (int) event.getX();int y = (int) event.getY();switch (event.getAction()) {case MotionEvent.ACTION_DOWN:mLastMotionX = x;mLastMotionY = y;mCounter++;isReleased = false;isMoved = false;postDelayed(mLongPressRunnable, 3000);// 按下 3秒後調用線程break;case MotionEvent.ACTION_MOVE:if (isMoved)break;if (Math.abs(mLastMotionX - x) > TOUCH_SLOP|| Math.abs(mLastMotionY - y) > TOUCH_SLOP) {// 移動超過閾值,則表示移動了isMoved = true;}break;case MotionEvent.ACTION_UP:// 釋放了isReleased = true;break;}return true;}}

public class LongMainActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);LinearLayout.LayoutParams layout = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);View v = new LongPressView1(LongMainActivity.this);v.setLayoutParams(layout);setContentView(v);v.setOnLongClickListener(new View.OnLongClickListener() {@Overridepublic boolean onLongClick(View v) {Toast.makeText(LongMainActivity.this, "abcdef",Toast.LENGTH_SHORT).show();return false;}});}}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.