How to select a mesh element as the selected

I have a GridView that uses an array adapter to populate data.

By default, when a GridView displayed, I have to show one of the selected items. I used gridview.setselected() but did not display the GridView element as selected (I mean that the background of the element does not change). Is there a way to show a specific item selected when loading a grid view. Please suggest

+7
android gridview
source share
5 answers

In the getView() adapter, do the following

 if(row != null) { if(position == selectedPosition){ set required background color } else { set background color to Color.TRANSPARENT } } 

In the onItemClick method, set the value of Adapter.selectedPosition and call notifydatasetchanged() , and then execute the required logic.

in the <GridView> xml listSelector to android:color/transparent

+1
source share

I struggled with this a bit yesterday, before realizing that what I really wanted was to test the item. i.e.

 gridview.setItemChecked(position, true); 
+14
source share

GridView.setSelected() actually inherited from View and just sets the entire GridView in your layout as selected.

What you are looking for is GridView.setSelection(int position) to select the current element in the GridView , starting at zero position.

Another useful feature is GridView.getFirstVisblePostion() , which can be used to store the current location in the GridView (if it is large and scrollable) so that it can be restored when you are restored from the state of the instance (say, during rotation) or otherwise case.

When working on such things, it is always useful to view the Android Developer Documentation for your widget / object.

+5
source share

I hope this helps you

  gridView.requestFocusFromTouch(); gridView.setSelection(1); 
+2
source share

Check with the following method.

 GridView.setBackgroundResource(R.drawable.new_image_to_be_shown); 

This will allow you to change the background of your selected item as a new image.

And if you want to change the color of the selected item, use -

 GridView.setBackgroundColor(int color); 

This will solve your problem.

-one
source share

All Articles