How to unselect an item in gridview on second clic

2019-06-27 20:45发布

I was trying to give background colour to selected items on GridView and I did it successfully using the following code-

gv.setOnItemClickListener(new OnItemClickListener() {  // gv is object of GridView

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            gv.getChildAt(arg2).setBackgroundColor(Color.rgb(125, 125, 125));

        }
    });

Now I want to remove the given background colour when clicked on each item the next time. How can I do it ? Also, when clicked again the background colour should appear and on next click background colour should be removed.

1条回答
看我几分像从前
2楼-- · 2019-06-27 20:57

You can check the current color background and then perform some conditional operation to update the view accordingly.

gv.setOnItemClickListener(new OnItemClickListener() {  // gv is object of GridView
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                            long arg3) {

        View view = gv.getChildAt(arg2);


        int desiredBackgroundColor = android.graphics.Color.rgb(125, 125, 125);

        ColorDrawable viewColor = (ColorDrawable) view.getBackground();

        if(viewColor == null) {
            view.setBackgroundColor(desiredBackgroundColor);
            return;
        }

        int currentColorId = viewColor.getColor();

        if(currentColorId == desiredBackgroundColor) {
            view.setBackgroundColor(Color.TRANSPARENT);
        } else {
            view.setBackgroundColor(desiredBackgroundColor);
        }

    }
});
查看更多
登录 后发表回答