Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set focus on any item of listview in android

I have a listview which contains textviews as its elements.

  1. Now I want the first item of the list to be automatically focused when I launch the application
  2. How can I set the focus on any item of the list when I click on the some other view for example a button?
like image 209
sarvesh Avatar asked Jul 02 '10 18:07

sarvesh


4 Answers

Setting selection and setting focus are two different things. If you want to just setSelection to some item then you can use below code.

    mListView.setSelection(position);

But this definitely does not mean the Listview is focused.For focussing you have to use

    mListView.requestFocus();

For changing focus on click of a button you can place the code on onClick() of the button.

like image 137
Abhilasha Avatar answered Oct 03 '22 07:10

Abhilasha


ListView has a setSelected method that takes the index of the item in the list.

like image 28
Robby Pond Avatar answered Oct 03 '22 07:10

Robby Pond


for me the problem was solved by

listView.setItemsCanFocus(true);
like image 30
Lukas Hanacek Avatar answered Oct 03 '22 07:10

Lukas Hanacek


I guess I was in the same situation. I wanted to be able to control the focus of the listview programmatically with buttons .

One solution is to deal with the setFocusableInTouchMode, but I've never achieved to make it work.

The other solution is to forget about the focus and use a checkable listview. First set your listview to "single choice mode" in XML or in java : Mylistview.setChoiceMode(1)

Then you'll be able to check any item you want with Mylistview.setItemChecked(position, true)

So when you lunch the application (OnCreate), use Mylistview.setItemChecked(0, true) to check your first item.

Then if you want your button to select the next item for exemple, use :

Mylistview.setItemChecked(Mylistview.getCheckedItemPosition() + 1, true)

You can specify the look when the item is checked or not and there's different pre-built chekable listviews.

If you want more explanations, see my post

like image 33
Jecimi Avatar answered Oct 03 '22 07:10

Jecimi