I have taken a sample program from a book that stores the text size and text. when I am running the program again, the text size is being decreased. Can anyone help me out I am new to android
public void onClick(View v) {
//Getting the SharedPreference object
prefs = getSharedPreferences(prefName, 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());
// Saves the values
editor.commit();
//Display file saved message
Toast.makeText(getBaseContext(), "Font size saved Successfully!", Toast.LENGTH_SHORT).show();
}
});
// Loading the shared Prefernces object
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
// Set the TextView font size to the previously saved values
float fontSize = prefs.getFloat(FONT_SIZE_KEY, 12);
// init the SeekBar and EditText
seekBar.setProgress((int)fontSize);
editText.setText(prefs.getString(TEXT_VALUE_KEY, ""));
editText.setTextSize(seekBar.getProgress());
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
@Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
// Change the font size of the EditText
editText.setTextSize(progress);
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onStopTrackingTouch(SeekBar arg0) {
}
});
You cast your
float fontSizetointwhen you pass it toseekBar.setProgress(). This makes it lose its fractional part, and therefore become smaller. Then you retrieve this rounded value back fromseekBarand calleditText.setTextSize()with it. Clearly it should get smaller, as the value has lost its fractional part.Try setting max value for your progress to be a large value (
seekBar.setMax(1000000000)), callseekBar.setProgress((int)(fontSize * 10000000))initially, and inonProgressChangeddoeditText.setTextSize( ((float) progress) / 10000000 ). What we do here is basically represent a floating point number in an integer form by multiplying it with a large value. See, if you multiply float 1.234 by 1000, you get 1234.0, which can now be converted to int without any loss of factional part. To convert it back, we first convert our int 1234 to float 1234.0, then divide by 1000. And since your original program worked with percent values in progress bar, we set the maximum value to be 100 times larger than the coefficient we use to convert numbers between int and float forms. This way we preserve the original functionality of your program.