我正在尝试通过屏幕上的按钮增加和减少声音的音量。我在这里有代码:

//variables
float leftVolume = 0.5f;
float rightVolume = 0.5f;

public void lowerVolume(View view)
{ float decrement = 0.2f;
    rightVolume -= decrement;
    leftVolume -= decrement;
    Log.d("Values","This is the value of volume"+ leftVolume);
}

public void raiseVolume(View view)
{ float increment = 0.2f;
    rightVolume = ++increment;
    leftVolume = ++increment;
    Log.d("Values","This is the value of volume"+ rightVolume);
}

日志显示了一些疯狂的值,例如当我单击rasieVolume时,它升至1.2f并停留在该位置。

最佳答案

发生这种情况是因为您每次调用raiseVolume()时都会将float值设置为1.2。

public void raiseVolume(View view)
{ float increment = 0.2f; //you set increment here
    rightVolume = ++increment; //then simply increase it by 1
    leftVolume = ++increment;

    //...and so your volume will always be 1.2 at this point
    Log.d("Values","This is the value of volume"+ rightVolume);
}

解决此问题的方法是将音量设置为raiseVolume()方法的初始值OUTSIDE(您已经做过),然后在raiseVolume()方法内部将其递增。

像这样:
//variables
float leftVolume = 0.5f;
float rightVolume = 0.5f;

public void raiseVolume(View view)
{ float increment = 0.2f;
    rightVolume += increment; //change this line to this
    leftVolume += increment;  //change this line to this
    Log.d("Values","This is the value of volume"+ rightVolume);
}

10-07 20:47