Save value to preference
package app.test;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
public class Test extends Activity {
private SharedPreferences prefs;
private EditText editText;
private SeekBar seekBar;
private Button btn;
private String FONT_SIZE_KEY = "fontsize";
private String TEXT_VALUE_KEY = "textvalue";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.EditText01);
seekBar = (SeekBar) findViewById(R.id.SeekBar01);
btn = (Button) findViewById(R.id.btnSave);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//---get the SharedPreferences object---
//prefs = getSharedPreferences(prefName, MODE_PRIVATE);
prefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putFloat(FONT_SIZE_KEY, editText.getTextSize());
editor.putString(TEXT_VALUE_KEY, editText.getText().toString());
editor.commit();
Toast.makeText(getBaseContext(),
"Font size saved successfully!",
Toast.LENGTH_SHORT).show();
}
});
//---load the SharedPreferences object---
//SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
prefs = getPreferences(MODE_PRIVATE);
float fontSize = prefs.getFloat(FONT_SIZE_KEY, 12);
seekBar.setProgress((int) fontSize);
editText.setText(prefs.getString(TEXT_VALUE_KEY, ""));
editText.setTextSize(seekBar.getProgress());
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
editText.setTextSize(progress);
}
});
}
}
//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"
>
<SeekBar
android:id="@+id/SeekBar01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<EditText
android:id="@+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnSave"
android:text="Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Related examples in the same category