[英]Change font size using shared preference in fragment
I am changing the size of a TextView
with a Shared Preference.我正在使用共享首选项更改TextView
的大小。 I am absolutely sure that I have written the codes in settings correctly, so I am just not sure about my fragment that whether or not it is correct.我绝对确定我已经正确地在设置中编写了代码,所以我不确定我的片段是否正确。 I was wondering if someone would mind recognizing the problem and correcting it please.我想知道是否有人介意认识到问题并请纠正它。 Thanks谢谢
prefsize = this.getActivity().getSharedPreferences(prefnamesize, Context.MODE_PRIVATE);
tx.setTextSize(prefsize.getFloat(FONT_SIZE_KEY, 25));
This is not the right/best practice for this purpose这不是用于此目的的正确/最佳实践
Store all the text size or anything related to 'dp' or 'sp' in dimen.xml in values folder将所有文本大小或与“dp”或“sp”相关的任何内容存储在值文件夹中的 dimen.xml 中
Example :示例:
dimen.xml尺寸文件
<resources>
<dimen name="textSizeMedium">16sp</dimen>
</resources>
Access this to your layout file:访问您的布局文件:
<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>
or in Java code dynamically (Activity)或在 Java 代码中动态(活动)
tx.setTextSize(getResources().getDimension(R.dimen.textSizeMedium));
(Fragment) (分段)
tx.setTextSize(getActivity().getResources().getDimension(R.dimen.textSizeMedium));
It is maybe too late, but I found the way.也许为时已晚,但我找到了方法。 In your dimens.xml has to go like this在你的 dimens.xml 必须像这样
<resources>
<dimen name="code_editor_size1">11sp</dimen>
</resources>
Then, in Java, when the user press the size Button, need to go this然后,在Java中,当用户按下大小按钮时,需要走这个
settings.edit().putString("textSize", String.valueOf((long)((float)getResources().getDimension(R.dimen.code_editor_size1)))).commit();
And finally, to use in the text view最后,在文本视图中使用
if (settings.getString("textSize", "").equals("")) {
}
else {
textSize = Double.parseDouble(settings.getString("textSize", ""));
code.setTextSize(TypedValue.COMPLEX_UNIT_PX, (float)textSize);
}
I want to mention that when I get the value, I got it with a Double variable, that was the only way I could have done this, and code is an id of an edit text我想提一下,当我得到这个值时,我得到了一个 Double 变量,这是我能做到的唯一方法,而代码是一个编辑文本的 id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.