Set highlighted item in GridView on Android
Asked Answered
E

1

1

Sometimes I am really amazed to see that simple things have hard to find solutions.

I have a GridView with 6 columns and multiple rows. Each item is a square having a color as background. When I select an item, it gets highlighted as the listSelector is set

<GridView
        android:id="@+id/listFontColors"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_gravity="center_horizontal"
        android:layout_margin="8dip"
        android:drawSelectorOnTop="true"
        android:gravity="center"
        android:horizontalSpacing="3dp"
        android:listSelector="@drawable/color_list_selected"
        android:numColumns="6"
        android:padding="0dip"
        android:scrollbars="none"
        android:stretchMode="columnWidth"
        android:verticalSpacing="3dp" />

When I open the layout, containing the GridView I want to highlight the previous selected item. As the adapter behind it has an ArrayList<Object> is easy to find what position needs to be highlighted. The problem is performing actual highlight.

I did a lot of testing:

listColors.requestFocus();
listColors.setSelection(9);

if (v != null) {
    v.requestFocus();
    v.setPressed(true);
    v.setSelected(true);
}
listColors.performItemClick(listColors, 9, listColors.getItemIdAtPosition(9));

None of this worked. Any ideas?

Execratory answered 9/4, 2013 at 9:12 Comment(0)
A
3

The simplest way is to save the position and check it inside your Adapter class inside getView() method.

if(selected_position = position){
    view.setBackgroundResource(selected_resource_id);
}
else{
    view.setBackgroundResource(resource_id);
}

And then just call notifyDataSetChanged() on your Adapter.

Arenas answered 9/4, 2013 at 9:20 Comment(1)
So you are saying, drop the listSelector and make 2 items and based on position, either load one or another ? I am amazed to see how a simple thing like this is missing from default implementationExecratory

© 2022 - 2024 — McMap. All rights reserved.