//将音量开关设置为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;
}
}
太感谢了。:)