我的切换按钮出现问题,我总是关闭力量。按钮代码:
public void getToggle(View view) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
PackageManager pm = getPackageManager();
ComponentName compName = new ComponentName(getApplicationContext(),
LowBatteryReceiver.class);
pm.setComponentEnabledSetting(compName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(MainActivity.this, "Modalità risparmio attivata", Toast.LENGTH_LONG).show();
TextView textView = (TextView)findViewById(R.id.risparmiostate);
textView.setText("Modalità risparmio on");
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
}else{
PackageManager pm = getPackageManager();
ComponentName compName = new ComponentName(getApplicationContext(),
LowBatteryReceiver.class);
pm.setComponentEnabledSetting(compName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(MainActivity.this, "Modalità risparmio disattivata", Toast.LENGTH_LONG).show();
TextView textView = (TextView)findViewById(R.id.risparmiostate);
textView.setText("Modalità risparmio off");
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", false); // value to store
editor.commit();
}
}
和onCrerate
public SharedPreferences preferences;
/** Called when the activity is first created. */
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
togglebutton.setChecked(true);
}
else
{
togglebutton.setChecked(false);
}
有什么想法吗?我试了一切。谢谢。我的logcat不起作用(我不知道为什么)。没有给我看任何东西。
答案 0 :(得分:1)
更改
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
到
preferences = getPreferences(MODE_PRIVATE);
在Activity的onCreate
中,因为在getToggle
方法
答案 1 :(得分:1)
尝试使用
if (tgpref == true)
或
if(tgpref)
代替
if(tgpref = true)。
尝试在Oncreate()中初始化TextView textView = (TextView)findViewById(R.id.risparmiostate);
。
同时从SharedPreferences
删除SharedPreferences preferences = getPreferences(MODE_PRIVATE);
因为您已在全球范围内声明。