How to unselect an item in gridview on second click in android?

妖精的绣舞 提交于 2019-12-10 17:29:54

问题


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:


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);
        }

    }
});


来源:https://stackoverflow.com/questions/25834273/how-to-unselect-an-item-in-gridview-on-second-click-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!