如何在Android中第二次单击取消选择在gridview的一个项目? [英] How to unselect an item in gridview on second click in android?

查看:341
本文介绍了如何在Android中第二次单击取消选择在gridview的一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是想给背景色上的GridView选定的项目,我成功地用下面的code一样 -

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.

推荐答案

您可以检查当前的背景颜色,然后执行一些有条件的操作相应地更新视图。

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

    }
});

这篇关于如何在Android中第二次单击取消选择在gridview的一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆