1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ListPreferenceで各項目の数値とフォントサイズを連動させる

Posted at

#ListPreferenceで各項目の数値とフォントサイズを連動させる

xmlで設定されたvaluesをコード中で取得→編集→再設定でむりやりサイズ変更
カスタムPreferenceのほうが綺麗なんだろうけどとりあえず実装するならばという感じで。

Screenshot_2017-11-11-01-09-242.png

preferece用xml

<ListPreference
    android:defaultValue="40"
    android:entries="@array/pref_font_size_titles"
    android:entryValues="@array/pref_font_size_values"
    android:key="font_size"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    android:title="@string/pref_title_font_size" />

strings.xml

<string name="pref_title_font_size">文字サイズ</string>
<string-array name="pref_font_size_titles">
    <item>30</item>
    <item>35</item>
    <item>40</item>
    <item>45</item>
    <item>50</item>
    <item>55</item>
    <item>60</item>
    <item>65</item>
    <item>70</item>
</string-array>
<string-array name="pref_font_size_values">
    <item>30</item>
    <item>35</item>
    <item>40</item>
    <item>45</item>
    <item>50</item>
    <item>55</item>
    <item>60</item>
    <item>65</item>
    <item>70</item>
</string-array>

このpreferenceを管理するpreferenceFragmentのonCreate()内

ListPreference basePreference = (ListPreference) findPreference("font_size");
// 取得
CharSequence[] entrys = basePreference.getEntries();
CharSequence[] entryValues = basePreference.getEntryValues();
// 編集
SpannableString[] createEntrys = new SpannableString[entrys.length];
for (int i = 0; i < basePreference.getEntries().length; i++) {
    String name = entrys[i].toString();
    int size = Integer.parseInt(entryValues[i].toString());
    SpannableString entry = new SpannableString(name);
    entry.setSpan(new AbsoluteSizeSpan(size), 0, name.length(), SPAN_EXCLUSIVE_EXCLUSIVE);
    createEntrys[i] = entry;
}
// 再設定
basePreference.setEntries(createEntrys);
bindPreferenceSummaryToValue(basePreference);
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?