change selected gridview cell background in android?

897 views Asked by At

i want to change background color of gridview item,when user select the gridview item? so that user understand that he/she selected the images please help me ...Thanks in advances

public class Gallery extends Activity implements
        OnItemClickListener {

    private GridView sdcardImages;
    ArrayList<String> IPath = new ArrayList<String>();
    String imagePath;
    private ImageAdapter imageAdapter;
     GridView grid = sdcardImages;
    private Display display;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      try{
          // Request progress bar
          requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
          setContentView(R.layout.gallery);
          Button selpic = (Button) findViewById(R.id.gallery);
          display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

          setupViews();
          setProgressBarIndeterminateVisibility(true);
          loadImages();
       /*   sdcardImages.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

              public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                             int position, long arg3) {
                  try{
//sdcardImages.setBackground(position);

                      int columnIndex = 0;
                      String[] projection = {MediaStore.Images.Media.DATA};
                      Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                              projection,
                              null,
                              null,
                              null);
                      if (cursor != null) {
                          columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                          cursor.moveToPosition(position);
                          imagePath = cursor.getString(columnIndex);
                      }
                      if(IPath.contains(imagePath))
                      {

                              Toast.makeText(getApplicationContext(),"Removed",Toast.LENGTH_SHORT).show();
                          IPath.remove(imagePath);
                          Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
                      }
                      else{
                              Toast.makeText(getApplicationContext(),"Selected",Toast.LENGTH_SHORT).show();
                          IPath.add(imagePath);
                          Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
                          }
                  }
                  catch (Exception e)
                  {
                      Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                  }

                  //Toast.makeText(MainActivity.this, "LONG PRESS", Toast.LENGTH_SHORT).show();
                  //set the image as wallpaper
                  return true;
              }
          });*/
          selpic.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                 try{
                     Intent intentMessage = new Intent(Gallery.this,
                             GalleryUpload.class);
                     intentMessage.putStringArrayListExtra("IMAGE", IPath);
                     startActivity(intentMessage);
                 }
                 catch (Exception e)
                 {
                     e.printStackTrace();
                     Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                 }
              }
          });
      }
      catch (Exception e)
      {
          e.printStackTrace();
          Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
      }
    }

    /**
     * Free up bitmap related resources.
     */
    protected void onDestroy() {
        super.onDestroy();

        final int count = grid.getChildCount();
        ImageView v = null;
        for (int i = 0; i < count; i++) {
            v = (ImageView) grid.getChildAt(i);
            ((BitmapDrawable) v.getDrawable()).setCallback(null);
        }
    }
    /**
     * Setup the grid view.
     */
    private void setupViews() {
        sdcardImages = (GridView) findViewById(R.id.sdcard);
       // sdcardImages.setNumColumns(display.getWidth()/95);
        sdcardImages.setChoiceMode(2);
        sdcardImages.setClipToPadding(false);
        sdcardImages.setOnItemClickListener(Gallery.this);
        imageAdapter = new ImageAdapter(getApplicationContext());
        sdcardImages.setAdapter(imageAdapter);

    }
    /**
     * Load images.
     */
    private void loadImages() {
        final Object data = getLastNonConfigurationInstance();
        if (data == null) {
            new LoadImagesFromSDCard().execute();
        } else {
            final LoadedImage[] photos = (LoadedImage[]) data;
            if (photos.length == 0) {
                new LoadImagesFromSDCard().execute();
            }
            for (LoadedImage photo : photos) {
                addImage(photo);
            }
        }
    }
    /**
     * Add image(s) to the grid view adapter.
     *
     * @param value Array of LoadedImages references
     */
    private void addImage(LoadedImage... value) {
        for (LoadedImage image : value) {
            imageAdapter.addPhoto(image);
            imageAdapter.notifyDataSetChanged();
        }
    }

    /**
     * Save bitmap images into a list and return that list.
     *
     * @see android.app.Activity#onRetainNonConfigurationInstance()
     */
    @Override
    public Object onRetainNonConfigurationInstance() {
        final GridView grid = sdcardImages;
        final int count = grid.getChildCount();
        final LoadedImage[] list = new LoadedImage[count];

        for (int i = 0; i < count; i++) {
            final ImageView v = (ImageView) grid.getChildAt(i);
            list[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
        }

        return list;
    }



    /**
     * Async task for loading the images from the SD card.
     *
     * @author Mihai Fonoage
     *
     */
    class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {

        /**
         * Load images from SD Card in the background, and display each image on the screen.
         *
         * @see android.os.AsyncTask#
         * doInBackground(Params[])
         */
        @Override
        protected Object doInBackground(Object... params) {
            //setProgressBarIndeterminateVisibility(true);
            Bitmap bitmap = null;
            Bitmap newBitmap = null;
            Uri uri = null;

            // Set up an array of the Thumbnail Image ID column we want
            String[] projection = {MediaStore.Images.Thumbnails._ID};
            // Create the cursor pointing to the SDCard
            Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                    projection, // Which columns to return
                    null,       // Return all rows
                    null,
                    null);
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
            int size = cursor.getCount();
            // If size is 0, there are no images on the SD Card.
            if (size == 0) {
                //No Images available, post some message to the user
            }
            int imageID = 0;
            for (int i = 0; i < size; i++) {
                cursor.moveToPosition(i);
                imageID = cursor.getInt(columnIndex);
                uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
                try {
                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                    if (bitmap != null) {
                        newBitmap = Bitmap.createScaledBitmap(bitmap, 150,150, true);
                        bitmap.recycle();
                        if (newBitmap != null) {
                            publishProgress(new LoadedImage(newBitmap));
                        }
                    }

                } catch (IOException e) {
                    //Error fetching image, try to recover
                }
            }
            cursor.close();
            return null;
        }
        /**
         * Add a new LoadedImage in the images grid.
         *
         * @param value The image.
         */
        @Override
        public void onProgressUpdate(LoadedImage... value) {
            addImage(value);
        }
        /**
         * Set the visibility of the progress bar to false.
         *
         * @see android.os.AsyncTask#onPostExecute(Object)
         */
        @Override
        protected void onPostExecute(Object result) {
            setProgressBarIndeterminateVisibility(false);
        }
    }
    /**
     * Adapter for our image files.
     * @author Mihai Fonoage
     */
    class ImageAdapter extends BaseAdapter {

        private Context mContext;
        private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();

        public ImageAdapter(Context context) {
            mContext = context;
        }

        public void addPhoto(LoadedImage photo) {
            photos.add(photo);
        }

        public int getCount() {
            return photos.size();
        }

        public Object getItem(int position) {
            return photos.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            final ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(mContext);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setPadding(1, 1, 1, 1);
            imageView.setImageBitmap(photos.get(position).getBitmap());

            return imageView;
        }
    }

    /**
     * A LoadedImage contains the Bitmap loaded for the image.
     */
    private static class LoadedImage {
        Bitmap mBitmap;

        LoadedImage(Bitmap bitmap) {
            mBitmap = bitmap;
        }

        public Bitmap getBitmap() {
            return mBitmap;
        }
    }
    /**
     * When an image is clicked, load that image as a puzzle.
     */
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

        try{
//sdcardImages.setBackground(position);

            int columnIndex = 0;
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                    projection,
                    null,
                    null,
                    null);
            if (cursor != null) {
                columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToPosition(position);
                imagePath = cursor.getString(columnIndex);
            }
            if(IPath.contains(imagePath))
            {

                Toast.makeText(getApplicationContext(),"Removed",Toast.LENGTH_SHORT).show();
                IPath.remove(imagePath);
                //Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
            }
            else{


                Toast.makeText(getApplicationContext(),"Selected",Toast.LENGTH_SHORT).show();
                IPath.add(imagePath);
                //Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
System.gc();
    }

}

gallery.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/insidepage1"
    android:weightSum="1">


    <GridView
        android:id="@+id/sdcard"
        android:layout_width="fill_parent"
        android:layout_height="438dp"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"
        android:numColumns="2"
        android:choiceMode="multipleChoice"
        android:listSelector="@drawable/grid_selector"
        android:layout_weight="1.22" />
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Selected Images"
            android:layout_marginTop="5dp"
            android:id="@+id/gallery" />

</LinearLayout>

grid_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/pressedback" />
    <item android:state_focused="true" android:drawable="@drawable/pressedback" />
    <item android:state_selected="true" android:drawable="@drawable/pressedback" />
    <item android:state_checked="true" android:drawable="@drawable/pressedback" />
    <item android:state_activated="true" android:drawable="@drawable/pressedback" />
    <item android:state_active="true" android:drawable="@drawable/pressedback" />
    <item android:state_long_pressable="true" android:drawable="@drawable/pressedback" />


</selector>
2

There are 2 answers

1
Borra Suneel On

Here you are added image view as dynamic right.Better need two create another layout for gridview adapter and inflate that layout then you will simple change that gridview cell background easily.In that layout you take linear-layout in that create one image-view ,set all margens 10dp for that image-view.So here image-view have four sides you have gap.That you will setBackground that linear-layout based on the position.

** <LinearLayout
            android:id="@+id/front"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="4dp"
            android:background="@color/white"
            android:orientation="vertical"
            android:paddingBottom="2dp" >



                <ImageView
                    android:id="@+id/profileImage"
                    android:layout_width="match_parent"
                    android:layout_height="100dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginBottom="10dp
                    android:contentDescription="@string/app_name"
                   />
</ImageView>
</LinearLayout>**

I Hope it will help to you...
0
Borra Suneel On
public class SearchProfileGridAdapter extends BaseAdapter {

    private Context context;
    private LayoutInflater inflator;
    private ArrayList<String> descriptionContent;
    public static boolean btnDoubleClickGridFlag = false;

    public SearchProfileGridAdapter(Context context,ArrayList<String> descriptionContent,String from) {
        this.context = context;
        inflator = LayoutInflater.from(context);
        this.from=from;
        listener=this;

    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        String des="";
        if (convertView == null) {
            convertView = inflator.inflate(R.layout.grid_item,parent,false);
            holder = new ViewHolder();

            holder.person_shortlist=(ImageView)convertView.findViewById(R.id.person_shortlist);


            convertView.setTag(holder);

        }else
        {

            holder = (ViewHolder) convertView.getTag();

        }

    holder.person_shortlist.setBackGround()//TODO
}
private static class ViewHolder {
        private ImageView person_shortlist;
    }