GirdView Items color change on select and previously selected item should show normal color

7.8k Views Asked by At

My GridView has a Image and text with gray color on select of any item i need to change that gray color of text and image to some other color(orange), and on select of other grid item i need change previously selected items to default grey color and selected one to orange..

i tried with some solutions but didnt get my proper output.. please help me with this problem this is what i tried :

private int previousSelectedPosition = -1;

 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            ImageView selectedImageView = (ImageView) gridView.findViewById(R.id.groupbyImage);
            TextView selectedTextView= (TextView) gridView.findViewById(R.id.groupbyHeader);
            if (previousSelectedPosition != position && previousSelectedPosition!=-1) {
                selectedImageView.setSelected(false);
                // Set the last selected View background color as deselected item
                selectedImageView.setColorFilter(getResources().getColor(R.color.gridsepration));
                // Set the last selected View text color as deselected item
                selectedTextView.setTextColor(getResources().getColor(R.color.gridsepration));
            } else {

                selectedTextView.setTextColor(getResources().getColor(R.color.violet));
                selectedImageView.setColorFilter(getResources().getColor(R.color.violet));
            }
            // Set the current selected view position as previousSelectedPosition
            previousSelectedPosition = position;

        }
    });

finally i got the solution .. find below the solution.

4

There are 4 best solutions below

0
On BEST ANSWER

I got the solution ,Thanks to all who responded back.

here is what i did.

In my adpater

 public HashMap<Integer, Boolean> hashMapSelected;

In My Adapter Constructor

     hashMapSelected = new HashMap<>();
    for (int i = 0; i < headers.size(); i++) {
        hashMapSelected.put(i, false);
    }

In my adapter getView

 if (hashMapSelected.get(position) == true) {
        viewHolder.imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.violet));
        viewHolder.textView.setTextColor(ContextCompat.getColor(mContext, R.color.violet));
    } else {
        viewHolder.imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.gridsepration));
        viewHolder.textView.setTextColor(ContextCompat.getColor(mContext, R.color.gridsepration));
    }

one Extra Method to clear the other item in adapter

 public void makeAllUnselect(int position) {
    hashMapSelected.put(position, true);
    for (int i = 0; i < hashMapSelected.size(); i++) {
        if (i != position)
            hashMapSelected.put(i, false);
    }
}

finally my grid view setOnItemClickListener

adapter.makeAllUnselect(position);
adapter.notifyDataSetChanged();

final my adapter looks like this

public class DataAdapter extends BaseAdapter {
   private Context mContext;
   private TypedArray images;
   private List<String> headers;
   public HashMap<Integer, Boolean> hashMapSelected;

public DataAdapter(Context context, TypedArray images, List<String> headers) {
    this.mContext = context;
    this.images = images;
    this.headers = headers;
    hashMapSelected = new HashMap<>();
    for (int i = 0; i < headers.size(); i++) {
        hashMapSelected.put(i, false);
    }
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return images.length();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

public void makeAllUnselect(int position) {
    hashMapSelected.put(position, true);
    for (int i = 0; i < hashMapSelected.size(); i++) {
        if (i != position)
            hashMapSelected.put(i, false);
    }
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ViewHolder viewHolder;

    if (convertView == null) {
        convertView = LayoutInflater.from(mContext).inflate(R.layout.groupby_grid_item, parent, false);
        viewHolder = new ViewHolder(convertView);
        convertView.setTag(viewHolder);

    } else
        viewHolder = (ViewHolder) convertView.getTag();
    viewHolder.textView.setText(headers.get(position));
    viewHolder.imageView.setImageResource(images.getResourceId(position, -1));


    if (hashMapSelected.get(position) == true) {
        viewHolder.imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.violet));
        viewHolder.textView.setTextColor(ContextCompat.getColor(mContext, R.color.violet));
    } else {
        viewHolder.imageView.setColorFilter(ContextCompat.getColor(mContext, R.color.gridsepration));
        viewHolder.textView.setTextColor(ContextCompat.getColor(mContext, R.color.gridsepration));
    }
    return convertView;
}


private class ViewHolder {
    TextView textView;
    ImageView imageView;

    public ViewHolder(View view) {
        textView = (TextView) view.findViewById(R.id.groupbyHeader);
        imageView = (ImageView) view.findViewById(R.id.groupbyImage);
    }
}
}

And my GridView OnItemClick

 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            selectedGroupBy = getHeaders().get(position);
            adapter.makeAllUnselect(position);
            adapter.notifyDataSetChanged();
        }
    });
3
On

Try this code it is working it is a sample working code, in this on selecting and item in grid view the background color gets changed along with the text color. And also the previous selected item gets deselected and as it was before.In this i have also used a textview.

below is the xml code for grid view.

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#e8594c"
    >
    <TextView
        android:id="@+id/tv_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#f85d4f"
        android:layout_marginBottom="15dp"
        android:padding="10dp"
        />
    <GridView
        android:id="@+id/gv"
        android:layout_width="650dp"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:numColumns="3"
        android:background="#d84521"
        android:verticalSpacing="2dp"
        android:horizontalSpacing="2dp"
        android:stretchMode="columnWidth"
        android:gravity="left"
        android:layout_below="@id/tv_message"
        >
    </GridView>
</RelativeLayout>

now the java file code is below:

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.app.Activity;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.res.Resources;


public class MainActivity extends Activity {
    private int previousSelectedPosition = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final GridView gv = (GridView) findViewById(R.id.gv);
        final TextView tv_message = (TextView) findViewById(R.id.tv_message);

        // Initializing a new String Array
        String[] plants = new String[]{
                "Catalina ironwood",
                "Cabinet cherry",
                "Pale corydalis",
                "Pink corydalis",
                "Belle Isle cress",
                "Land cress",
                "Orange coneflower",
                "Coast polypody",
                "Water fern"
        };

        // Populate a List from Array elements
        final List<String> plantsList = new ArrayList<String>(Arrays.asList(plants));

        // Data bind GridView with ArrayAdapter (String Array elements)
        gv.setAdapter(new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, plantsList){
            public View getView(int position, View convertView, ViewGroup parent) {

                // Return the GridView current item as a View
                View view = super.getView(position,convertView,parent);

                // Convert the view as a TextView widget
                TextView tv = (TextView) view;

                // set the TextView text color (GridView item color)
                tv.setTextColor(Color.DKGRAY);

                // Set the layout parameters for TextView widget
                RelativeLayout.LayoutParams lp =  new RelativeLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT
                );
                tv.setLayoutParams(lp);

                // Get the TextView LayoutParams
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)tv.getLayoutParams();

                // Set the width of TextView widget (item of GridView)
                params.width = getPixelsFromDPs(MainActivity.this,168);

                // Set the TextView layout parameters
                tv.setLayoutParams(params);

                // Display TextView text in center position
                tv.setGravity(Gravity.CENTER);

                // Set the TextView text font family and text size
                tv.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);

                // Set the TextView text (GridView item text)
                tv.setText(plantsList.get(position));

                // Set the TextView background color
                tv.setBackgroundColor(Color.parseColor("#FFFF4F25"));

                // Return the TextView widget as GridView item
                return tv;
            }
        });

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Get the selected item text
                String selectedItem = parent.getItemAtPosition(position).toString();

                // Display the selected item text to app interface
                tv_message.setText("Selected item : " + selectedItem);

                // Get the current selected view as a TextView
                TextView tv = (TextView) view;

                // Set the current selected item background color
                tv.setBackgroundColor(Color.parseColor("#FF9AD082"));

                // Set the current selected item text color
                tv.setTextColor(Color.BLUE);

                // Get the last selected View from GridView
                TextView previousSelectedView = (TextView) gv.getChildAt(previousSelectedPosition);

                // If there is a previous selected view exists
                if (previousSelectedPosition != -1)
                {
                    // Set the last selected View to deselect
                    previousSelectedView.setSelected(false);

                    // Set the last selected View background color as deselected item
                    previousSelectedView.setBackgroundColor(Color.parseColor("#FFFF4F25"));

                    // Set the last selected View text color as deselected item
                    previousSelectedView.setTextColor(Color.DKGRAY);
                }

                // Set the current selected view position as previousSelectedPosition
                previousSelectedPosition = position;
            }
        });
 }

    // Method for converting DP value to pixels
    public static int getPixelsFromDPs(Activity activity, int dps){
        Resources r = activity.getResources();
        int  px = (int) (TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dps, r.getDisplayMetrics()));
        return px;
    }
}

the output of this code is:

Before

enter image description here

After

enter image description here

Hope it helps you out!

0
On

I your Model (grid view Object ):

  1. You should put one boolean variable to know which one is selected or not.
  2. when you select one of them you should set true the boolean variable of , if you want another cards will inselect you should set false the boolean variable of that grid view.
  3. After any change (like selecting one of the gird view) you have to call mAdapter.notifyDataSetChanged();
2
On

You need to add one more field for selection in your model class. So you can set selection from your getView() method of your adapter. Use viewHolder in your adapter.

public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;

    if (convertView == null) {

        convertView = LayoutInflater.from(context).inflate(
                R.layout.your_row_file, null);

        holder = new ViewHolder();

        holder.selectedImageView = (ImageView) convertView
                .findViewById(R.id.groupbyImage);
        holder.selectedTextView = (TextView) convertView
                .findViewById(R.id.groupbyHeader);

        convertView.setTag(holder);

    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    if (yourArrayList.get(position).getSelected()) {
            selectedTextView.setTextColor(getResources().getColor(R.color.violet));
            selectedImageView.setColorFilter(getResources().getColor(R.color.violet));
        } else {
     // Set the last selected View background color as deselected item 
            selectedImageView.setColorFilter(getResources().getColor(R.color.gridsepration));
            // Set the last selected View text color as deselected item 
            selectedTextView.setTextColor(getResources().getColor(R.color.gridsepration));
     }


    convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        //   =========== Update IsSelected Value in Day Array======

           boolean isSelected=yourArrayList.get(position).getSelected();
           yourArrayList.get(position).setSelected(!isSelected);

           notifyDataSetChanged();
        }
    });
    return convertView;
}