开发者

Can preferences be accessed in an XML layout?

I am working to implement some simple preferences to an开发者_Python百科 app I have and I am trying to figure out how to use a preference to manipulate a view defined in an XML file. I have a List with the following LinearLayout (player_row.xml) being used for each row:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <ImageView android:id="@+id/player_icon"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center"/>
  <TextView android:id="@+id/player_name"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textSize="30sp"
   android:textColor="#F0F0F0"
   android:layout_weight="1"
   android:layout_marginLeft="5dp"/>
  <TextView android:id="@+id/player_score"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textSize="30sp"
   android:textColor="#F0F0F0"/>
</LinearLayout>

Right now I am specifying the textSize attribute manually. I'd like to create a preference menu that lets the user select from several options, say "Small", "Medium", and "Large". I figure I should be able to set up the arrays for the entry and font sizes and then reference that in player_row.xml, but I don't seem to be able to.

preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
   android:key="preference_main">
   <ListPreference
      android:key="fontSizePreference"
      android:title="Font size"
      android:entries="@array/fontSizeList"
      android:entryValues="@array/fontSizeList_Values"/>
</PreferenceScreen>

arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string-array name="fontSizeList">
    <item>Small</item>
    <item>Medium</item>
    <item>Large</item>
  </string-array>
  <string-array name="fontSizeList_Values">
    <item>22sp</item>
    <item>26sp</item>
    <item>30sp</item>
  </string-array>
</resources>

If this can't be done, what is the appropriate way to configure a layout using preferences? My searching has led me to find multiple resources on accessing the preferences programmatically but none of that seems to be the appropriate way to configure a layout defined in an XML file.


I think the procedure you are looking for is:

  1. Create settings screen & activity
  2. Once the user saves settings, let your backing PreferenceActivity save the settings into a file (using getPreferences(MODE_PRIVATE).edit().putString(PREF_FONT_SIZE, yourSetting).commit()
  3. In your main activity#onCreate, load the layout using setContentView
  4. Load your preferences there as well
  5. Get the views via findViewById and set the font size as it's loaded from the preferences
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜