代码之家  ›  专栏  ›  技术社区  ›  Thomas

可以在XML布局中访问首选项吗?

  •  2
  • Thomas  · 技术社区  · 15 年前

    我正在努力实现对我所拥有的应用程序的一些简单的首选项,我正在尝试找出如何使用首选项来操作在XML文件中定义的视图。我有一个列表,其中每行使用以下linearlayout(player_row.xml):

    <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>
    

    现在我正在手动指定textsize属性。我想创建一个首选项菜单,允许用户从几个选项中进行选择,如“小”、“中”和“大”。我认为我应该能够为条目和字体大小设置数组,然后在player_row.xml中引用这些数组,但是我似乎不能。

    首选项.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>
    

    语言:

    <?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>
    

    如果不能这样做,使用首选项配置布局的适当方法是什么?我的搜索使我在以编程方式访问首选项时找到了多个资源,但这些资源似乎都不是配置XML文件中定义的布局的合适方法。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Sebastian Roth    15 年前

    我想你要找的程序是:

    1. 创建设置屏幕和活动
    2. 用户保存设置后,让您的备份首选项活动将设置保存到文件中(使用 getPreferences(MODE_PRIVATE).edit().putString(PREF_FONT_SIZE, yourSetting).commit()
    3. 在您的主要活动中创建后,使用setContentView加载布局
    4. 在那里加载您的首选项
    5. 通过获取视图 findViewById 并在从首选项加载时设置字体大小