代码之家  ›  专栏  ›  技术社区  ›  Pritish

有没有更简单的方法来编写以下需求并压缩代码?

  •  0
  • Pritish  · 技术社区  · 6 年前

    所以我现在要做的是

    img1、img2、img3、img4、img5

    所以我将click listener设置为

         @Override
        public void onClick(View view) {
            try {
                switch (view.getId()) {
                    case R.id.img1:
    // Set background image as blue to img1 and set //black for others
                        break;
                    case R.id.img2:
    // Set background image as blue to img2 and set //black for others including the previous one
                        break;
                    case R.id.img3:
                        break;
                    case R.id.img4:
                        break;
                    case R.id.img5:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
    

    所以我一次又一次地重复这些步骤。我能把这个代码压缩成更短的格式吗,比如把以前的图像存储在视图中,给当前的图像上色??简而言之,压缩这段代码的最佳方法是什么?

    1 回复  |  直到 6 年前
        1
  •  2
  •   TDG    6 年前

    您可以将所有图像的背景色设置为黑色 try 语句,然后仅将选定图像的背景设置为蓝色:

    @Override
    public void onClick(View view) {
        //Set black background for all the imags
        try {
            switch (view.getId()) {
                case R.id.img1:
                    // Set background image as blue to img1 for others
                    break;