我正在尝试通过更改首选项来更新我的应用背景颜色,但是从未达到onSharedPreferenceChanged方法。首选项已成功更改,但我的侦听器无法正常工作:
MainActivity:
public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private RecyclerView mRecyclerView;
private ContactsAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void onResume() {
super.onResume();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettings.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSettings.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, MyPreferenceActivity.class);
startActivity(intent);
return true;
case R.id.action_favorite:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(key.equals("color")) {
String color = sharedPreferences.getString("color", "3");
int colorId = Integer.valueOf(color);
// Alterar background
ViewGroup viewGroup = (ViewGroup) ((ViewGroup) (findViewById(android.R.id.content))).getChildAt(0);
if (colorId == 1) {
viewGroup.setBackgroundColor(Color.WHITE);
} else if (colorId == 2) {
viewGroup.setBackgroundColor(Color.YELLOW);
} else if (colorId == 3) {
viewGroup.setBackgroundColor(Color.RED);
}
}
}
}
MyPreferenceActivity:
public class MyPreferenceActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
从来没有调用过onSharedPreferenceChanged方法,我使它起作用的唯一方法是直接在onResume内部实现OnSharedPreferenceChangeListener方法,但是有时它可以正常工作,有时却不能,并且无法达到该方法。
答案 0 :(得分:1)
在创建名为PreferenceActivity
的{{1}}时,将调用MyPreferenceActivity
的{{1}},从而使监听者注销。
一种解决方法是,从onPause()
中的监听器MainActivity
而不是onStop()
取消注册。
onPause()
MainActivity
答案 1 :(得分:1)
仅当MainActivity位于前台时,共享首选项registerOnSharedPreferenceChangeListener才有效,否则它将在onPause中取消注册。