简体   繁体   中英

Focus 1st item in a listview when starting an activity android

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?

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

采用

listview.setselection(thenumber/position);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM