Android中同一应用程序的活动之间共享数据的示例:
public class OptionsActivity extends Activity {
SharedPreferences _settings;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
_settings = getSharedPreferences(STATIC_PROPERTY.PREFS_NAME, 0);
Spinner spBackground = (Spinner) findViewById(R.id.backgroundsThemeSelect);
spBackground.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
SharedPreferences.Editor editor = _settings.edit();
int backgroundID = 0;
switch (pos){
default:
case 0:
backgroundID = R.drawable.grass;
break;
case 1:
backgroundID = R.drawable.earth;
break;
case 2:
backgroundID = R.drawable.water;
break;
}
editor.putInt("background", backgroundID);
// Commit the edits!
editor.commit();
}
});
....
}
然后在要使用此设置的活动或后台代码上:
public class ConsumerViewextends View 实现 GameListener { public static final String PREFS_NAME = "PrefsFile";
public ConsumerView(Context context, AttributeSet attrs) {
super(context, attrs);
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
int backgroundID = settings.getInt("background", R.drawable.water);
setBackgroundDrawable(_appResources.getDrawable(backgroundID));
....
}
....
}
希望这可以帮助 :)