Android开关语句无法正常工作

时间:2016-05-03 17:57:06

标签: android switch-statement case

我有一个用作按钮的imageview,我设置了onclick方法,在里面我声明了一个switch语句,我需要每次点击按钮我应该调用不同的情况,所以我设置了case 0 ,案例1,案例2,案例3,并且我为每个案例提出了我想要的方法,但是,每次我点击按钮,案例似乎混在一起,它只调用案例0和案例3,我不# 39;知道出了什么问题,我在一个较旧的项目上使用这个代码并且运行良好,但现在我无法看到出了什么问题。

这是我的代码:

 // i tried to use static, final int but still it's the same problem.
 private int textnumber = 0;
 button_text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (textnumber) {

        case 0:
            //changeTextColor(int) method, for each number it changes the text's color.
            changeTextColor(1);
            Toast.makeText(getApplicationContext(),"text color is 1",Toast.LENGTH_SHORT).show();
            break;
        case 1:
            changeTextColor(2);
            Toast.makeText(getApplicationContext(),"text color is 2",Toast.LENGTH_SHORT).show();
            break;
        case 2:
            changeTextColor(3);
            Toast.makeText(getApplicationContext(),"text color is 3",Toast.LENGTH_SHORT).show();
            break;
        case 3:
            changeTextColor(4);
            Toast.makeText(getApplicationContext(),"text color is 4",Toast.LENGTH_SHORT).show();
            break;

    }

        }
    });

 private void changeTextColor(int id){
    //mRenderer is a class that uses GLES 2.0 (glsurfaceview etc...);
    //mObjectsData is a class that i use to store different datas
    if(id == 1){
    textnumber = 1;
    mObjectsData.mTextColor = "yellow";
    mRenderer.requestRender();
    }
    else if(id == 2){
        textnumber = 2;
        mObjectsData.mTextColor = "green";
        mRenderer.requestRender();
    }
    else if(id == 3){
        textnumber = 3;
        mObjectsData.mTextColor = "blue";
        mRenderer.requestRender();
    }
    else if(id == 4){
        textnumber = 4;
        mObjectsData.mTextColor = "red";
        mRenderer.requestRender();
    }
}

2 个答案:

答案 0 :(得分:1)

看起来您必须在其他地方更改变量textnumber。切换语句或android工作室没有任何神奇之处可以让它无缘无故地改变你的变量。附:您的代码可以大大减少:

 private int textnumber = 0;
 private String[] colors = new String[] { "yellow", "green", "blue","red" };

 //some method
    button_text.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           int oldColor = textnumber;
           textnumber = (textnumber + 1) % 4;
           Toast.makeText(getApplicationContext(),"text color is " + textnumber,Toast.LENGTH_SHORT).show();
           mObjectsData.mTextColor = colors[oldColor];
           mRenderer.requestRender();

       }
   });

答案 1 :(得分:0)

也许你和我一样犯了同样的错误。看看我以前的问题

android studio OnClicklistener no reaction on first Click

我的错误是设置onclicklistener并声明按钮。我应该只做一件事。