数据共享同一个应用程序的活动之间在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 {0} {0} 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));
....
}
....
}
希望这有助于:)
谢谢,刚才我正在看一些共享首选项的教程,heh.Thanks,你的例子可以帮助我更好地理解它的工作原理!祝你今天愉快 ! –
任何时候都没问题:) – CarlosB