4
votes

I have a CardScrollView that has multiple items in it and I would like to be able to pull up a menu on an item, similar to the built in Timeline.

I know Card cannot have a specific menu attached to it so I have the menu prepared at the Activity level.

However, something seems to be swallowing all onKeyDown events.

public class HostsView extends CardScrollView {
  private String TAG = "HostsView";
  private HostsCardScrollAdapter cards;
  private Activity parent;

  public HostsView(Activity parent, HostDatabase hostDb) {
    super(parent);
    cards = new HostsCardScrollAdapter(parent);
            //populates the cards and what not
    this.setAdapter(cards);
    this.activate();
  }

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
                  //I never see this log
    Log.d(TAG, "Key event " + event.toString());
    if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
        parent.openOptionsMenu();
        return true;
    }
    return super.onKeyDown(keyCode, event);
  }
}
2

2 Answers

4
votes

If you only need to handle a simple tap on a card in a CardScrollView, you can call setOnItemClickListener to attach an AdapterView.OnItemClickListener, just as you would with a standard Android ListView. This is typically much simpler than working with GestureDetector for this basic use case.

3
votes

yesterday I came across the same problem. I solved it with a GestureDetector, as the GDK documentation recommends. Here is the code I used:

private GestureDetector mGestureDetector;

@Override
public void onCreate(Bundle savedInstanceState) {
mGestureDetector = createGestureDetector(this);
}


private GestureDetector createGestureDetector(Context context) {
    GestureDetector gestureDetector = new GestureDetector(context);
    gestureDetector.setBaseListener( new GestureDetector.BaseListener() {
        @Override
        public boolean onGesture(Gesture gesture) {
            if (gesture == Gesture.LONG_PRESS || gesture == Gesture.TAP) {
                Log.d(MainActivity.TAG, "Tap"); //When I tap the touch panel, I only get LONG_PRESS
                openOptionsMenu();
                return true;
            } else if (gesture == Gesture.TWO_TAP) {

                return true;
            } else if (gesture == Gesture.SWIPE_RIGHT) {

                return true;
            } else if (gesture == Gesture.SWIPE_LEFT) {

                return true;
            }
            return false;
        }
    });
    return gestureDetector;
}

@Override
public boolean onGenericMotionEvent(MotionEvent event) {
    if (mGestureDetector != null) {
        return mGestureDetector.onMotionEvent(event);
    }
    return false;
}

Your menu should open now!