我有一个浮动按钮(它很快就是一个按钮),当我点击它时,它会启动一个服务和按钮更改图标。我试着用这种方式:
mFab = (FloatingActionButton)findViewById(R.id.fabbutton);
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_play));
mFab.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (RunService.isRunning) {
RunService.stopRun(MainActivity.this);
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_play));
SharedPreferences.Editor editor = getSharedPreferences("com.mypck.asd", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
} else {
startService(new Intent(MainActivity.this, RunService.class));
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_pause));
}
}
});
并检索状态:
SharedPreferences sharedPrefs = getSharedPreferences("com.mypck.asd", MODE_PRIVATE);
mFab.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
但不是以这种方式工作,因为setChecked
方法是用于切换按钮..而我的是一个简单的按钮!我怎么解决?
答案 0 :(得分:1)
所以,只需保存SharedPreference
中的按钮状态,如 true 和 false ,当服务在if-else
条件下运行时 p>
请看下面的代码。
SharedPreferences.Editor editor = getSharedPreferences("com.mypck.asd", MODE_PRIVATE).edit();
if (RunService.isRunning) {
RunService.stopRun(MainActivity.this);
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_play));
editor.putBoolean("NameOfThingToSave", true);
} else {
startService(new Intent(MainActivity.this, RunService.class));
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_pause));
editor.putBoolean("NameOfThingToSave", false);
}
editor.commit();
<强>更新强>
要检索您必须执行的值,
SharedPreferences sharedPrefs = getSharedPreferences("com.mypck.asd", MODE_PRIVATE);
boolean buttonState = sharedPrefs.getBoolean("NameOfThingToSave", true);
if(buttonState)
{
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_play));
}else{
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_pause));
}
替换
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_play));
上面的代码。
答案 1 :(得分:0)
好的,只需按照您的喜好保存状态。
mFab.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences.Editor editor = getSharedPreferences("com.mypck.asd", MODE_PRIVATE).edit();
if (RunService.isRunning) {
RunService.stopRun(MainActivity.this);
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_play));
editor.putBoolean("NameOfThingToSave", true);
} else {
startService(new Intent(MainActivity.this,RunService.class));
mFab.setDrawable(getResources().getDrawable(R.drawable.ic_pause));
editor.putBoolean("NameOfThingToSave", false);
}
editor.commit();
}
});