Reputation: 1
I am developing an app that when I press a button ,It starts a new activity (ContactList.java) that contains a listview called mContactList. When the activity starts I want the first item of the listview to be automatically focused.
I tried something like that:
ContactList.java
mContactsList.requestFocus(mContactsList.getFirstVisiblePosition());
I have also created this two xml resources to ensure that when the view is focused a rectangle is displayed around the item of the listview:
selected_rectangle.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:color="@color/blue"
android:width="5dp"/>
</shape>
selector_contact_list.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:drawable="@drawable/selected_rectangle"/> </selector>
For some reason this code doesn´t work and I am not able to set focus on the first item of the list (since no rectangle appears around the first item of the list).
Can someone give me clues what is happening?
Upvotes: 0
Views: 1210
Reputation: 1777
Please note that setting focus and setting selection are two different things.. and I think you mean the second one, if so try this:
listViewName.setSelection(positionOfItem);
if that didn't work, try requestFocusFromTouch()
before calling setSelection()
method.
and if that didn't work, try this:
listViewName.setItemChecked(positionOfItem, true);
Or this:
listViewName.smoothScrollToPosition(positionOfItem);
For other solutions try the answers in this link: Android ListView setSelection() does not seem to work
Upvotes: 1