2015-01-21 24 views
0

我正在使用觸摸監聽器來顯示和隱藏一些音量控件,在ACTION_DOWN上顯示控件並在ACTION_UP上隱藏它們。我希望能夠在不擡起手指的情況下觸摸控件,我嘗試使用ACTION_MOVE動作,並且無法使其正常工作,因爲事件從未觸發。我想過拖曳事件,但我不確定這是否適合。我會在這種情況下使用什麼樣的動作事件?

public boolean onTouch(View v, MotionEvent e) 
{ 
    if(v == audioControls) 
    { 
     if(e.getAction() == MotionEvent.ACTION_DOWN) 
      showVolumeControls(); 
     else if(e.getAction() == MotionEvent.ACTION_UP) 
      hideVolumeControls(); 

    } 


    else if(e.getAction() == MotionEvent.ACTION_MOVE) 
    { 
     if(v == mute) 
     //Do stuff with this volume control 
    } 

    return true; 
} 

@Demand答案,閱讀我的評論 - 這裏是代碼:

public boolean onTouch(View v, MotionEvent e) 
{ 
if(v == mute && e.getAction() == MotionEvent.ACTION_MOVE) 
{ 
Toast.makeText(getApplicationContext(), "Muted.", Toast.LENGTH_SHORT).show(); 
hideVolumeControls(); 
return true; 
} 
else 
return false; 
} 

回答

0

所以,你需要uderstand觸摸事件是如何工作的機器人。如果觸及View1,請爲該視圖設置onTouchListener,併爲該事件返回true - 其他視圖將永遠不會從同一個鏈中獲取運動事件。

對於你來說,這意味着如果你觸及「audioControls」,那麼除非你釋放你的手指,否則沒有其他視圖可以捕捉到運動事件。

您可以在您的onTouch方法中返回false。在這種情況下,audioControls的parentView也會捕獲所有的motionEvents。但是,視圖層次結構中不屬於audioControls的視圖不會捕獲motionEvent。

您需要捕捉容器中的所有動作事件以供您查看,併爲自己發送它們。這是在不同視圖中從一個鏈接捕捉motionEvents的唯一方法。

更新: 我會盡量多解釋一下。 想象一下,你有佈局是這樣的:

<LinearLayout id="@+id/container"> 
    <View id="@+id/view1"/> 
    <View id="@+id/view2"/> 
</LinearLayout> 

而且要降落在廠景和移動你的手指視圖2。 Android觸摸事件流程無法做到這一點。只有一個視圖可以捕捉整個事件鏈。 所以你需要添加onTouchListener到你的容器,並做這樣的事情。

public boolean onTouch(MotionEvent event) { 
    float x = event.getX(); 
    float y = event.getY(); 
    for (int i = 0; i<container.getChildCount(); i++) { 
    View child = container.getChildAt(i); 
    if (x>child.getLeft() && x < child.getRight() && y < child.getBottom() && y > child.getTop()) { 
     /*do whatever you want with this view. Child will be view1 or view2, depends on coords;*/ 
     break; 
    } 
    } 
} 

請注意,我在那裏寫了這段代碼,可能會犯一些錯誤。我試圖展示這個想法。

+0

你能舉個例子嗎?我在單個視圖中用我的action_move試了一下,並嘗試在屏幕上隨意拖動(而不是擡起),然後在視圖上移動以查看它是否觸發了事件,但事實並非如此。我把代碼放在我的編輯 – joe 2015-01-21 10:09:20

+0

@joe我更新了我的答案。 – 2015-01-23 11:19:47