How to place border on a selected item in Listview?

Asked

Viewed 435 times

2

How to place a border on a Listview item when the user selects that item in the android app?

  • 1

    Your ListView is multi-selection?

  • @Androiderson is actually Simple Selection

  • If it is simple selection, it makes no sense to highlight the selected item. Use the selector default and trigger any necessary event as soon as the item is selected.

  • @Androiderson yes, but the user will select and then yes, should pass to the next page, it is more question of UX

1 answer

1


Follow these steps:

1 - Add the attribute android:choiceMode à Listview,

to allow selecting only one line:

android:choiceMode="singleChoice"

to select more than one line:

android:choiceMode="multipleChoice"

To customize the appearance of the selection requires a Selector.

2 - Create, in the folder res/drawable, the drawable to be used in the Selector:

list_item_selected.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

        <solid android:color="cor do fundo quando selecionado"/>
        <stroke 
            android:color="cor da borda quando selecionado"
            android:width="3dip"/>
</shape>

list_item_unselected.xml

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

        <solid android:color="cor do fundo quando não selecionado"/>
        <stroke 
            android:color="cor da borda quando não selecionado"
            android:width="3dip"/>
</shape>

Put colors to your liking!
If in any case you want the color to be the Listview background use @android:color/transparent

3 - Create the Selector:

list_item_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

   <item android:drawable="@drawable/list_item_selected" android:state_pressed="true"/>
   <item android:drawable="@drawable/list_item_selected" android:state_selected="true"/>
   <item android:drawable="@drawable/list_item_selected" android:state_activated="true"/>

    <!-- não seleccionada -->
    <item android:drawable="@drawable/list_item_unselected"/>
</selector> 

4 - Assign Selector to background of item of the list:

android:background="@drawable/list_item_selector"

Note: I didn’t test, I hope I didn’t get anything wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.