【问题标题】:How to cycle over 3 types of values in array [android]如何在数组中循环 3 种类型的值 [android]
【发布时间】:2016-06-15 13:13:05
【问题描述】:

我想知道每次单击按钮时按 color1 -> color3 -> color 2 的顺序循环遍历下面示例数组的算法。

int[] colorList = new int[]{color1, color2, color3};

目前,我尝试像下面的示例那样做,但无法做到。 如果可能的话,你会帮我一把吗?我找不到按我想要的顺序进行转换的解决方案。我很想收到您的来信!

void updateIndicators(int position) {
      for (int i = 0; i < indicators.length; i++) {
          indicators[i].setBackgroundResource(
                  i == position ? R.drawable.indicator_selected : R.drawable.indicator_unselected
          );
      }
  }

【问题讨论】:

  • 这里为什么需要循环?如果您只有 3 个项目,只需对这些索引进行硬编码。它将只有 3 行代码。在这里使用循环没有任何好处。

标签: android


【解决方案1】:

首先在您的活动类文件中声明全局变量,如下所示:

int buttonclickcount=0;

在您的点击监听器中:

yourbutton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            buttonclickcount++;
            if(buttonclickcount%3==0)
            {
                //set color 1 from array
            }
            else if(buttonclickcount%3==1)
            {

                //set color 2 from array
            }
            else if(buttonclickcount%3==2)
            {

                //set color 3 from array
            }
        }
    });

【讨论】:

    【解决方案2】:

    也许是这样的?

    public int getNextPosition(int prevPosition){
        int maxPosition=2;
        return (prevPosition+maxPosition)%(maxPosition+1);
    }
    

    当输入为 0 时返回 2

    当输入为 2 时为 1

    当输入为 1 时为 0

    所以colorList[0]->colorList[2]->colorList[1]

    您还可以添加另一个函数来返回颜色:

    public int nextColor(int prevPosition){
        return colorList[getNextPosition(prevPosition)];
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 2018-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多