Highlighting a Grey Icon in ImageView to White when the whole list entry is clicked in ListView, then reverting back

StackOverflow https://stackoverflow.com/questions/21197256

Question

I have a list of icons and text in a list view. The icons and text are grey in the list with a white background. When a user clicks an entry the icons and text are supposed to turn to white and the background of the entry box turns orange.

I got the text to turn white and the background to turn orange when pressed I am having trouble with the images turning from grey to white, when pressed and back again, when it's no longer pressed.

I have two sets are images or icons. One set is grey for inactive(not pressed) and one set is white that is active (pressed) in the resources folder.

It loads the grey icons when the app is loaded through an DrawerItemAdapter earlier in the code.

mThumbsId is an array with R.drawable images.

I tried changing the image to white icon version when clicked. But how to revert back to grey when it is no longer selected?

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view,
                int position, long id) {
            // TODO Auto-generated method stub

            Object o = mDrawerList.getItemAtPosition(position);
            String pen = o.toString();
            Toast.makeText(getApplicationContext(), "You have chosen: " + " " + pen, Toast.LENGTH_SHORT).show();
            ImageView image = (ImageView)view.findViewById(R.id.menuImage);

            image.setBackgroundResource(mThumbIds[position]);

        }   

    }
Was it helpful?

Solution

You have to write selector programmatically and set it to the background to ImageView.

Like:

StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
     getResources().getDrawable(white image id position));
states.addState(new int[] {},
     getResources().getDrawable(grey image id position));
image.setBackgroundResource(states);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top