Set highlighted item in GridView on Android

a 夏天 提交于 2019-12-11 11:25:13

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15897911/set-highlighted-item-in-gridview-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!