//set the Volume switch to ON
swVolume.setChecked(true);
//attach a listener to check for the changes in state
swVolume.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
//check the current state before we display the screen
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);
}
Can someone tell me why can't I add the if else code into the listener? and is the listener function just to view the switch status?
I saw one example on the internet:
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) {
but I don't really know why do I need to type the if-else statement twice, cause even if I remove the if-else statement here the code is still working fine. Can someone explain to me?
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;
}
}
Thank you so much. :)