Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting setOnKeyListener for a ListView

Tags:

android

I have been trying to set an OnKeyListener, but I am not sure how I can get the selected row on the ListView in the View.OnKeyListener. The v parameter always gives me the ListView, not the selected row. Any idea how to solve this problem? Thank you.

listView.setOnKeyListener(new OnKeyListener() {

    public boolean onKey(View v, int keyCode, KeyEvent event) {
        //....
    }

}
like image 706
n179911 Avatar asked Dec 20 '25 08:12

n179911


1 Answers

You can use AbsListView.getSelectedView() method:

public boolean onKey(View v, int keyCode, KeyEvent event) {
    ListView listView = (ListView) v;
    if (listView.getSelectedView() != null) {
        // (cast if necessary) and use selected view
    }
}

If you interested in selected item position, id or associated object you can use AdapterView.getSelectedItemPosition(), AdapterView.getSelectedItemId() and AdapterView.getSelectedItem() methods correspondingly.

like image 136
Bakhtiyor Avatar answered Dec 22 '25 00:12

Bakhtiyor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!