2014-06-05 79 views
1

我可以以編程方式爲視圖啓動長按事件嗎?我知道有燒製click事件performClick()函數,但我正在尋找長按事件我可以以編程方式爲視圖啓動長按事件嗎?

+0

嘗試實施longClickListener界面在你的活動或片段,將是這樣的:'MyActivity延伸活動實現onLongClickListener'那麼你可以重寫需要View作爲參數的onLongClick方法,並且只是編程式地將你的View對象傳遞給該方法並調用它。 – user3455363

+0

順便說一句你是否試圖執行內部長按的代碼?如果是,只需將其放入方法並致電 – user3455363

回答

0
 view.setOnLongClickListener(new OnLongClickListener() { 

     @Override 
     public boolean onLongClick(View v) { 


       //do your stuff here 

      return true; 
     } 
    }); 

那你怎麼做android系統中長按。或者在您的父類中實現onLongClickListener,然後添加未實現的方法

與您的看法。

view.setOnLongClickListener(this);

0

沒有內置函數,如performClick()。所以你必須自己實現這個系統。

你可以聽onTouchListener。然後在event.ACTION_DOWNevent.ACTION_UP的幫助下確定觸摸是否長按鍵並相應地執行操作。祝你好運!

2

view.performLongClick();它的存在對我來說...我

+1

請參閱:http://developer.android.com/reference/android/view/View.html#performLongClick%28%29 –

2

這一個工作:

view.performLongClick(); 
0
public static void longClickView(View v) { 

    final int viewWidth = v.getWidth(); 
    final int viewHeight = v.getHeight(); 

    final float x = viewWidth/2.0f; 
    final float y = viewHeight/2.0f; 

    long downTime = SystemClock.uptimeMillis(); 
    long eventTime = SystemClock.uptimeMillis(); 

    MotionEvent event = MotionEvent.obtain(downTime, eventTime, 
      MotionEvent.ACTION_DOWN, x, y, 0); 
    v.onTouchEvent(event); 

    eventTime = SystemClock.uptimeMillis(); 
    final int touchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop(); 
    event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, 
      x + touchSlop/2, y + touchSlop/2, 0); 
    v.onTouchEvent(event); 

    v.postDelayed(() -> { 
     long eventTime2 = SystemClock.uptimeMillis(); 
     MotionEvent event2 = MotionEvent.obtain(downTime, eventTime2, MotionEvent.ACTION_UP, x, y, 0); 
     v.onTouchEvent(event2); 
    }, (long) (ViewConfiguration.getLongPressTimeout() * 1.5f)); 
} 
相關問題