按钮事件
<Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="save" android:text="保存" />
package cn.itcast.SharedPreference; import java.util.Map; import cn.itcast.service.PreferenceService; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { /** Called when the activity is first created. */ private EditText nameText = null; private EditText ageText = null; PreferenceService svr = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); nameText = (EditText) this.findViewById(R.id.name); ageText = (EditText) this.findViewById(R.id.age); svr = new PreferenceService(this); Map<String, String> params = svr.getPreference(); nameText.setText(params.get("name")); ageText.setText(params.get("age")); } public void save(View v) { String nameString = nameText.getText().toString(); String ageString = ageText.getText().toString(); //获取Preferences的第二种方法 //this.getPreferences(MODE_PRIVATE); svr.save(nameString, Integer.valueOf(ageString)); Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show(); } }
package cn.itcast.service; import java.util.HashMap; import java.util.Map; import javax.security.auth.PrivateCredentialPermission; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class PreferenceService { private Context context; public PreferenceService(Context context) { this.context = context; } /** * 保存参数 * @param name * @param age */ public void save(String name, Integer age) { // TODO Auto-generated method stub SharedPreferences preferences = context.getSharedPreferences("itcast", Context.MODE_PRIVATE); Editor editor = preferences.edit(); editor.putString("name", name); editor.putInt("age", age); editor.commit(); } public Map<String, String> getPreference() { Map<String, String> params = new HashMap<String, String>(); SharedPreferences preferences = context.getSharedPreferences("itcast", Context.MODE_PRIVATE); params.put("name", preferences.getString("name", "")); params.put("age", String.valueOf(preferences.getInt("age", 0))); return params; } }