Andreas Gohr
Andreas Gohr

Reputation: 4935

ListView custom selected icon

I have a ListView where the user can select something:

<ListView
    android:id="@+id/poll_list"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:choiceMode="singleChoice"
    android:listSelector="#666" />

That works fine. When the user picks something, the item gets colored with #666. But I would prefer it to display a custom icon instead. Eg. a right aligned checkmark graphic.

I could include that graphic in my item's view. But how do I display it based on the state (without having to let the Adapter having to keep track of the checked state and invalidate all the data all the time)?

In CSS it would be a right aligned background graphic visible on :active only. But how to do it in Android? I think it should be possible with a custom drawable somehow.

Upvotes: 1

Views: 205

Answers (1)

Dan Mercer
Dan Mercer

Reputation: 459

You can use a 9-patch drawable such as this one to accomplish this effect:

9-patch drawable example

The black bars on the left and top tell Android to resize the drawable when necessary by stretching it in those areas. In this case, both of those areas are transparent, so it results in the check being right-aligned.

To use this in your code, just set the list selector to be the 9-patch drawable. Like so:

    lv.setSelector(R.drawable.ic_check_black_rightaligned);

Or like so:

    ...
    android:listSelector="@drawable/ic_check_black_rightaligned"
    ...

Upvotes: 2

Related Questions