I have a listview which contains textviews as its elements.
Your ListView should be like this:
<ListView
android:id="@+id/my_list"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_margin="10dp"
android:choiceMode="none"
android:focusable="true"
android:fadeScrollbars="false">
<requestFocus />
</ListView>
mListView.setSelection(3); //or any other number
ListView has a setSelected method that takes the index of the item in the list.
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.
for me the problem was solved by
listView.setItemsCanFocus(true);
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