1

我有一个PreferenceClass扩展类PreferenceActivity。这个类的代码如下:

public class Preferenceclass extends PreferenceActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // setContentView(R.layout.main2);
    addPreferencesFromResource(R.layout.preferences);

}}

我还有一个Shakelistener实现SensorListener. 这个类的代码如下:

    public class Shakelistener implements SensorListener {
    public void onSensorChanged(int sensor, float[] values) {
    // Some code
    }}

我需要能够从这个非活动类中访问首选项,但我不确定如何执行此操作。

编辑

这是我用来访问共享首选项的代码:

    String PREF_FILE_NAME = "preferences";

    SharedPreferences pref = mContext.getSharedPreferences(PREF_FILE_NAME , Context.MODE_PRIVATE);
    String myListPreference = pref.getString("listpref", "default choice");
    boolean cb = pref.getBoolean("checkBox", false);
    Toast.makeText(mContext, myListPreference+"-"+cb, Toast.LENGTH_LONG).show();

此代码没有给出任何错误,但它总是将 toast 评估为“默认选择-false”。

在这种情况下,我应该使用哪个 PREF_FILE_NAME?

4

1 回答 1

2

在非活动类的构造函数中获取一个Context实例,并使用它来调用所有此类方法。

像这样的东西:

public class NonActivityClass implements SensorListener{
Context mContext;
public NonActivtiyClass(Context context) {
this.mContext = context;
}
//Rest of your code
}

然后执行此操作以在您的 Activtiy 中创建该类的对象onCreate()

NonActivityClass nac = new NonActivityClass(this);
于 2012-07-02T17:29:12.830 回答