【Android 开发教程】修改首选项文件的默认名字

来源:互联网 发布:c语言新建项目 编辑:程序博客网 时间:2024/05/16 15:23

本章节翻译自《Beginning-Android-4-Application-Development》,如有翻译不当的地方,敬请指出。

原书购买地址http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/


在我的设备上面,默认的首选项名字是net.manoel.UsingPreferences_preferences.xml,这个名字是使用包名作为前缀的。然而,给首选项定义一个特殊的名字也是非常有益的。可以按照下面这么做。

public class AppPreferenceActivity extends PreferenceActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                PreferenceManager prefMgr = getPreferenceManager();        prefMgr.setSharedPreferencesName("appPreferences");        //---load the preferences from an XML file---        addPreferencesFromResource(R.xml.myapppreferences);    }}

这里,我们使用PreferenceManager这个类去设置首选项文件的名字为appPreferences.xml。

同时,修改UsingPreferencesActivity.java这个类。

public class UsingPreferencesActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);}public void onClickLoad(View view) {Intent i = new Intent("net.manoel.AppPreferenceActivity");startActivity(i);}public void onClickDisplay(View view) {/*SharedPreferences appPrefs = getSharedPreferences("net.manoel.UsingPreferences_preferences", MODE_PRIVATE); */        SharedPreferences appPrefs =                 getSharedPreferences("appPreferences", MODE_PRIVATE);DisplayText(appPrefs.getString("editTextPref", ""));}public void onClickModify(View view) {/*SharedPreferences appPrefs = getSharedPreferences("net.manoel.UsingPreferences_preferences", MODE_PRIVATE);*/        SharedPreferences appPrefs =                 getSharedPreferences("appPreferences", MODE_PRIVATE);SharedPreferences.Editor prefsEditor = appPrefs.edit();prefsEditor.putString("editTextPref", ((EditText) findViewById(R.id.txtString)).getText().toString());prefsEditor.commit();}private void DisplayText(String str) {Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();}}
当我们返回到应用并且修改首选项的时候,就会看到appPreferences.xml这个文件已经被创建了。