2014-10-02 60 views
0

我需要实现一个列表视图,当向一侧滑动一行时,所有其他行将滑动到另一侧。 我所有的行都会在屏幕上(.2-7行)。可滑动的列表视图

我知道我可以在适配器中获得视图。 但是我怎样才能得到被触摸的视图(没有点击)。

我不太清楚如何开始实施这个。

有什么建议?

感谢, 宜兰

回答

1

您可以使用View.setOnTouchListener(..)为。

下面是一些示例代码:

public class SwipeTouchListener implements View.OnTouchListener { 
    private ListView listView; 
    private View downView; 

    public SwipeTouchListener(ListView listView) { 
     this.listView = listView; 
    } 

    @Override 
    public boolean onTouch(View v, MotionEvent motionEvent) { 
     switch (motionEvent.getActionMasked()) { 
      case MotionEvent.ACTION_DOWN: 
       // swipe started, get reference to touched item in listview 
       downView = findTouchedView(motionEvent); 
       break; 
      case MotionEvent.ACTION_MOVE: 
       if (downView != null) { 
        // view is being swiped 
       } 
       break; 
      case MotionEvent.ACTION_CANCEL: 
       if (downView != null) { 
        // swipe is cancelled 
        downView = null; 
       }  

       break; 
      case MotionEvent.ACTION_UP: 
       if (downView != null) { 
        // swipe has ended 
        downView = null; 
       }    
       break; 
      } 
     } 
    } 

    private View findTouchedView(MotionEvent motionEvent) { 
     Rect rect = new Rect(); 
     int childCount = listView.getChildCount(); 
     int[] listViewCoords = new int[2]; 
     listView.getLocationOnScreen(listViewCoords); 
     int x = (int) motionEvent.getRawX() - listViewCoords[0]; 
     int y = (int) motionEvent.getRawY() - listViewCoords[1]; 
     View child = null; 
     for (int i = 0; i < childCount; i++) { 
      child = listView.getChildAt(i); 
      child.getHitRect(rect); 
      if (rect.contains(x, y)) { 
       break; 
      } 
     } 

     return child; 
    } 
} 

要使用此:

SwipeTouchListener swipeTouchListener = new SwipeTouchListener(listView); 
listView.setOnTouchListener(swipeTouchListener);