Search...

Sunday, November 13, 2011

How to set the custom background for currently selected and unselected gallery images in android


Step1: create two background images for selected and unselected images.
Step2: create new selector xml under drawable folder.
e.g:  gallery_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/unfocus"/>
<item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/focus"/>
<!-- Focused states -->
<item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/focus"/>
<item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/focus"/>
<!-- Pressed -->
<item android:state_pressed="true" android:drawable="@drawable/focus"/>
</selector>

Step3: Use this xml in your getView() method of your adapter.

public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);

i.setImageDrawable(galleyPhotos[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
80,70));
            i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(R.drawable. gallery_background);

return i;

No comments:

Post a Comment