我试图清理我的代码并创建一个仅用于SharedPreference更改的类。
这就是我目前所拥有的:
this.router.navigate(["/"]).then(result=>{window.location.href = 'http://www.cnn.com/';});
这个很好用。但是,只要我将此代码移动到我的支持类: 包com.example.rok.terroristinfo;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
prefs.registerOnSharedPreferenceChangeListener(listener);
}
SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if (key.equals("listEventType") || key.equals("listEventAge")) {
recreate();
}
}
};
}
从MainActivity类中调用它:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class SharedPreferencesInit {
private Context context;
private Activity activity;
private SharedPreferences prefs;
public SharedPreferencesInit(Context context, Activity activity) {
this.context = context;
this.activity = activity;
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
protected void recreateOnChange() {
prefs.registerOnSharedPreferenceChangeListener( new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// listener implementation
if (key.equals("listEventType") || key.equals("listEventAge")) {
activity.recreate();
}
}
};
}
}
它不起作用。有什么建议吗?