有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如果铃声音量达到最大值,如何打开开关?如果铃声音量小于最大值,如何关闭开关?

//将音量开关设置为ON

    swVolume.setChecked(true);

//附加侦听器以检查状态的更改

    swVolume.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
           }
    });

//在显示屏幕之前检查当前状态

      if(swVolume.isChecked()){
            AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            am.setStreamVolume(
                AudioManager.STREAM_RING,
                am.getStreamMaxVolume(AudioManager.STREAM_RING),
                0);       
      }
      else {
            swVolume.setChecked(false);
      } 

有人能告诉我为什么不能将if-else代码添加到侦听器中吗? 侦听器功能只是为了查看开关状态吗

我在网上看到了一个例子:

public class MainActivity extends Activity {


 private TextView switchStatus;
 private Switch mySwitch;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  switchStatus = (TextView) findViewById(R.id.switchStatus);
  mySwitch = (Switch) findViewById(R.id.mySwitch);

  //set the switch to ON 
  mySwitch.setChecked(true);
  //attach a listener to check for changes in state
  mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {

但是我真的不知道为什么我需要输入两次if-else语句,因为即使我在这里删除if-else语句,代码仍然可以正常工作。 谁能给我解释一下吗

    if(isChecked){
     switchStatus.setText("Switch is currently ON");
    }else{
     switchStatus.setText("Switch is currently OFF");
    }

   }
  });

  //check the current state before we display the screen
  if(mySwitch.isChecked()){
   switchStatus.setText("Switch is currently ON");
  }
  else {
   switchStatus.setText("Switch is currently OFF");
  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

} 

非常感谢。:)


共 (0) 个答案