package com.xiva.shared;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SharedActivity extends Activity {
/** Called when the activity is first created. */
private EditText format;
private EditText size;
private static final String TAG = "SharedActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) this.findViewById(R.id.saveButton);
Button showBtn = (Button) this.findViewById(R.id.showButton);
format = (EditText) this.findViewById(R.id.format);
size = (EditText) this.findViewById(R.id.size);
button.setOnClickListener(listener);
showBtn.setOnClickListener(listener);
}
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View paramView) {
Button button = (Button)paramView;
SharedPreferences prefere = SharedActivity.this.getSharedPreferences("xiva", Context.MODE_PRIVATE);
switch (button.getId()) {
case R.id.saveButton :
String formatStr = format.getText().toString();
String sizeStr = size.getText().toString();
//根据SharedPreferences得到编辑内容
Editor editor = prefere.edit();
editor.putString("format", formatStr);
try{
editor.putInt("size",Integer.parseInt(sizeStr));
}
catch(Exception e)
{
Toast.makeText(SharedActivity.this, "参数设置失败,文件大小只能输入数字!", Toast.LENGTH_LONG).show();
}
boolean result = editor.commit();//将editor提交
if(result){
Toast.makeText(SharedActivity.this, "参数设置成功!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(SharedActivity.this, "参数设置失败,", Toast.LENGTH_LONG).show();
}
break;
case R.id.showButton :
Log.i(TAG,"show");
Toast.makeText(SharedActivity.this, "显示", Toast.LENGTH_LONG).show();
String _str01 = prefere.getString("format", "");
format.setText(_str01);
break;
}
}
};
}
SharedPreferences prefere = SharedActivity.this.getSharedPreferences("xiva", Context.MODE_PRIVATE);
Editor editor = prefere.edit();
editor.commit();
程序运行后,将数据保存在本程序目录下的shared_prefs文件夹下。
SharedPreferences prefere = SharedActivity.this.getPreferences(MODE_PRIVATE);
getPreferences这个方法创建的是shared_prefs已SharedActivity(即程序名)为名称的xml配置文件。
this.createPackageContext(packageName, flags)
这个方法可以创建其他应用的上下文(context),因此这个配置也适合其他应用调用该配置文件!
完整代码见附件!