簡體   English   中英

使用片段中的共享首選項更改字體大小

[英]Change font size using shared preference in fragment

我正在使用共享首選項更改TextView的大小。 我絕對確定我已經正確地在設置中編寫了代碼,所以我不確定我的片段是否正確。 我想知道是否有人介意認識到問題並請糾正它。 謝謝

prefsize = this.getActivity().getSharedPreferences(prefnamesize, Context.MODE_PRIVATE);
tx.setTextSize(prefsize.getFloat(FONT_SIZE_KEY, 25));

這不是用於此目的的正確/最佳實踐

將所有文本大小或與“dp”或“sp”相關的任何內容存儲在值文件夾中的 dimen.xml 中

示例

尺寸文件

<resources>
    <dimen name="textSizeMedium">16sp</dimen>
</resources>

訪問您的布局文件:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    ...

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="@dimen/textSizeMedium" />  // <----- This is the way

    ...

</FrameLayout>

或在 Java 代碼中動態(活動)

tx.setTextSize(getResources().getDimension(R.dimen.textSizeMedium));

(分段)

tx.setTextSize(getActivity().getResources().getDimension(R.dimen.textSizeMedium));

也許為時已晚,但我找到了方法。 在你的 dimens.xml 必須像這樣

<resources>
<dimen name="code_editor_size1">11sp</dimen>
</resources>

然后,在Java中,當用戶按下大小按鈕時,需要走這個

settings.edit().putString("textSize", String.valueOf((long)((float)getResources().getDimension(R.dimen.code_editor_size1)))).commit(); 

最后,在文本視圖中使用

if (settings.getString("textSize", "").equals("")) {
    
}
else {
    textSize = Double.parseDouble(settings.getString("textSize", ""));
    code.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float)textSize);
}

我想提一下,當我得到這個值時,我得到了一個 Double 變量,這是我能做到的唯一方法,而代碼是一個編輯文本的 id

暫無
暫無

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

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