使用共享首选项记住用户在Android中喜欢的字体大小

时间:2015-10-01 13:28:44

标签: android sharedpreferences font-size android-sharedpreferences

我正在开发一款移动歌本Android应用程序。我已启用文本放大或缩小。我希望应用程序能够记住用户在将用户关闭特定歌曲时更喜欢的特定字体大小,甚至更好,即使用户关闭应用程序并再次打开它。以下是我尝试这样做的方法:

public void saveFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putFloat("fontsize",factor.getInt());
    editor.apply();
}

public void rememberFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    double factor = sharedPref.getString("fontsize","");
    factor.setInt();
}

以下是整个班级:

public class SongbookActivity extends AppCompatActivity {
private TextView wordMeaning;
private TextToSpeech convertToSpeech;
ScaleGestureDetector scaleGestureDetector;
public double factor;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dictionary);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarSongActivity);
    TextView textViewTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
    setSupportActionBar(toolbar);


    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    int dictionaryId = bundle.getInt("SONG._ID");
    int id = dictionaryId + 1;


    wordMeaning = (TextView)findViewById(R.id.dictionary);


    String title = bundle.getString("SONG._TITLE");
    String description = bundle.getString("SONG._LYRICS");

    final android.support.v7.app.ActionBar ab = getSupportActionBar();
    ab.setHomeAsUpIndicator(R.drawable.left);
    ab.setTitle(null);
    ab.setDisplayHomeAsUpEnabled(true);


    textViewTitle.setText(title);

    textViewTitle.setSelected(true);
   // textViewTitle.setMovementMethod(new ScrollingMovementMethod());

    wordMeaning.setTextIsSelectable(true);

    registerForContextMenu(wordMeaning);
    wordMeaning.setMovementMethod(new ScrollingMovementMethod());
    wordMeaning.setText(description);
    scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());


    }


//copy text or select
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    //user has long pressed your TextView
    menu.add(0, v.getId(), 0, "Song copied to Clipboard");

    //cast the received View to TextView so that you can get its text
    TextView yourTextView = (TextView) v;

    //place your TextView's text in clipboard
    ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
    clipboard.setText(yourTextView.getText());

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onTouchEvent(MotionEvent event) {


    if (event.getPointerCount() > 1) {
        scaleGestureDetector.onTouchEvent(event);
        return true;
    }
    return false;


}

public void saveFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putFloat("fontsize",factor.getInt());
    editor.apply();
}

public void rememberFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    double factor = sharedPref.getString("fontsize","");
    factor.setInt();
}

public class simpleOnScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        // TODO Auto-generated method stub
        float size = wordMeaning.getTextSize();
        Log.d("TextSizeStart", String.valueOf(size));

        float factor = detector.getScaleFactor();
        Log.d("Factor", String.valueOf(factor));

        float product = size*factor;
        Log.d("TextSize", String.valueOf(product));
        wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, product);

        size = wordMeaning.getTextSize();
        Log.d("TextSizeEnd", String.valueOf(size));
        return true;
    }
}



@Override
public boolean onOptionsItemSelected(MenuItem item) {
    double factor = 1;
    float size = wordMeaning.getTextSize();
    saveFont(View view);
    rememberFont(View view);
    Log.d("TextSizeStart", String.valueOf(size));
    switch (item.getItemId()) {
        case R.id.small_layout:
            factor = 0.5;
            break;
        case R.id.medium_layout:
            factor = 0.9;
            break;
        case R.id.large_layout:
            factor = 1.3;
            break;
        case R.id.xlarge_layout:
            factor = 1.8;
            break;
    }



    Log.d("Factor", String.valueOf(factor));

    double product = size*factor;
    Log.d("TextSize", String.valueOf(product));
    wordMeaning.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float)product);

    size = wordMeaning.getTextSize();
    Log.d("TextSizeEnd", String.valueOf(size));
    return super.onOptionsItemSelected(item);



}

}

我在尝试调用方法和方法声明时遇到错误。我是一个菜鸟,所以请告诉我你可能认为可以帮助我的所有细节,无论它多么微不足道。

3 个答案:

答案 0 :(得分:0)

在这里你将得到所有http://developer.android.com/training/basics/data-storage/shared-preferences.html 实际上你使用int存储在float中并试图获取字符串,所以请尝试下面的

public void saveFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("fontsize",factor.getInt());
    editor.commit();
}

从回来

public void rememberFont(View view){
    SharedPreferences sharedPref = getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    int  prevFont = sharedPref.getInt("fontsize",-1);

}

在-1中您可以设置默认字体

答案 1 :(得分:0)

如何做到这一点“光明”。

public void setVariable(float myFloat) {
    pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    editor = pref.edit();
    editor.putFloat("fontsize", myFloat);
    editor.commit();
}

public float getVariable() {
    pref = _context.getSharedPreferences("fontsize", Context.MODE_PRIVATE);
    return pref.getFloat("fontsize", 5.5/*a default value*/);
}

_context可以是一个属性。

EDIT1 :对于任何“保存”问题,此课程对我都很有效。根据需要更改此信息

public class SharedPreferencesManager {

    // Shared Preferences
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private Context _context;

    // Shared pref mode
    private final int PRIVATE_MODE_SHARED_PREF = 0;

    // Shared preferences file name
    private final String PREF_NAME = "blabla";

    /*KEYS para o sharedpreferences*/
    private final String KEY_TO_USE = PREF_NAME + "setFont";


    public SharedPreferencesManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE_SHARED_PREF);
        editor = pref.edit();
    }

    public void setFont(float keySize) {
        editor.putFloat(KEY_TO_USE, keySize);
        editor.commit();
    }

        public boolean getFont() {
        return pref.getFloat(KEY_TO_USE, 15/*your default value is in here (in sp)*/);
    }
}

要使用它,只需创建一个对象(传递上下文[活动])并在EditText / TextView的每次调用/膨胀中使用方法GET,并设置像这样的大小

myTextView.setTextSize(mSharedPreferencesManagerObject.getVariable())

对于所有这一切都有意义,在每个变焦变化时,你需要调用

mSharedPreference.setVariable(sizeHere)

它可以工作。如果没有,问题在于你的“OnZoomChange”逻辑/语义。

答案 2 :(得分:0)

如果您在使用SharedPreferences时遇到问题,请尝试使用this。这极大地简化了整个过程并在内部使用SharedPreferences。您所要做的就是复制项目中的源文件并使用它。

以下是一个例子:

在您的活动的onCreate()方法中,初始化TinyDB。

TinyDB tinyDB = new TinyDB(this);

然后像这样使用它:

tinyDB.putString("fontSize", "12");

String fontSize = tinyDB.getString("fontSize");

就这么简单。有许多方法在日常开发中非常有用,只需浏览一次源文件即可。希望能帮助到你。