簡體   English   中英

使用共享首選項來記住用戶在Android中首選的字體大小

[英]Using Shared preferences to remember the font size that a user prefers in Android

我正在開發一個移動歌曲本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);



}

}

嘗試調用方法以及方法聲明時出現錯誤。 我對此很菜鳥,所以請給我您可能認為可以幫助我的所有細節,無論它有多微不足道。

在這里,您將獲得所有的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中,您可以設置默認字體

只是一個“燈”,您將如何做到這一點。

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”邏輯/語義上。

如果您在使用SharedPreferences時遇到問題,請嘗試使用this 這極大地簡化了整個過程,並在內部使用SharedPreferences。 您要做的就是在項目中復制源文件並使用它。

這是一個例子:

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

TinyDB tinyDB = new TinyDB(this);

然后像這樣使用它:

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

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

就如此容易。 有許多方法在日常開發中非常有用,只需遍歷源文件一次即可。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM