-2

How can I disable onKeyDown of a listView? I want the onKeyDown of the activity to handle the keyEvent and only the keyEvent. Thanks.

coder
  • 10,460
  • 17
  • 72
  • 125
Vervatovskis
  • 2,277
  • 5
  • 29
  • 46
  • 1
    Its difficult to understand your question, can you please explain what do you want to achieve exactly? – Yaqub Ahmad Dec 20 '11 at 12:14
  • 1
    When my listview is focused, when i press the dpad_down key, i don't want that the listview receive the event and change the selected item, i want to do other action. – Vervatovskis Dec 20 '11 at 12:19

2 Answers2

0

Use this class

public class CustomListView extends ListView {

public CustomListView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if ((KeyEvent.KEYCODE_DPAD_UP == event.getKeyCode() || KeyEvent.KEYCODE_DPAD_DOWN == event.getKeyCode())) {
        //handle key events here
    }
    return false;
}

}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Tihomir Tashev
  • 185
  • 2
  • 9
0

If you are extending your listview from ListActivity then below will hep you.

onListItemClick:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    String item = (String) getListAdapter().getItem(position);
    Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}

OnKeyDown:

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    super.onKeyDown(keyCode, event);
        switch(keyCode)
        {
            case KeyEvent.KEYCODE_CAMERA:
             Toast.makeText(ListViewActivity.this, "Pressed Camera Button", Toast.LENGTH_SHORT).show();
                return true;
            case KeyEvent.KEYCODE_1:
             Toast.makeText(ListViewActivity.this, "Pressed 1", Toast.LENGTH_SHORT).show();
                return true;
            case KeyEvent.KEYCODE_HOME:
             Toast.makeText(ListViewActivity.this, "Pressed Home Button", Toast.LENGTH_SHORT).show();
                return true;

            case KeyEvent.KEYCODE_BACK:
             Toast.makeText(ListViewActivity.this, "Pressed Back Button", Toast.LENGTH_SHORT).show();
                finish();
                return true;
        }

        return false;
    }
Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149