1:Shared Perferencesà使用key—value保存数据
使用sss=getSharedPerferences(Activity.MODE_PRIVATE)取得SharedPerferences的实例,
使 uti=getSharedPerferences(Activity.MODE_PRIVATE).edit()取得SharedPerferences.Editor的实例
uti.putString(String,String)
uti.putBoolean(String,Boolean);
使用合适的方法保存你的数据
Uti.commit();执行保存
Sss.getString(String,String);
Sss.getBoolean(String,Boolean);
………
使用合适的方法取得你的数据
例如:package cao.org.android.sharedper;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SharedPerference_Activity extends Activity {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK){
SharedPreferences shared_close=getPreferences(0);
SharedPreferences.Editor shEditor_close=shared_close.edit();
shEditor_close.putString("but", string);
shEditor_close.commit();
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
private Button but_1,but_2;
private TextView text_1;
private String string="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
but_1=(Button)findViewById(R.id.but_1);
but_2=(Button)findViewById(R.id.but_2);
text_1=(TextView)findViewById(R.id.text_1);
SharedPreferences shared_1=getPreferences(Activity.MODE_PRIVATE);
string=shared_1.getString("but", "关闭");
text_1.setText("当前状态:"+string);
but_1.setOnClickListener(but_1_listener);
but_2.setOnClickListener(but_2_listener);
}
private OnClickListener but_1_listener=new Button.OnClickListener(){
@Override
public void onClick(View v) {
string="开启";
text_1.setText(string);
}
};
private OnClickListener but_2_listener=new OnClickListener() {
@Override
public void onClick(View v) {
string="关闭";
text_1.setText(string);
}
};
}
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/text_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
<Button
android:id="@+id/but_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="开启"
/>
<Button
android:id="@+id/but_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="关闭"
/>
</LinearLayout>