2010-11-18 62 views
2

我正在努力实现一些简单的偏好,我有一个应用程序,我想弄清楚如何使用首选项来操纵定义在XML文件中的视图。我有以下的LinearLayout(player_row.xml)的列表被用于每行:可以在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中引用它,但我似乎无法做到。

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

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

回答

1

我认为你正在寻找的过程是:

  1. 创建设置屏幕&活动
  2. 一旦用户保存设置,让你的后盾PreferenceActivity保存设置到文件(使用getPreferences(MODE_PRIVATE).edit().putString(PREF_FONT_SIZE, yourSetting).commit()
  3. 在您的主要活动#onCreate中,使用setContentView加载布局
  4. 将您的偏好加载到那里
  5. 获取v通过findViewById浏览并设置字体大小,因为它从首选项加载
+0

这就是我想我需要做的。我很希望有一种方法可以通过布局文件来完成。 – Thomas 2010-11-18 05:11:35

+1

这有什么用?你将需要另一个XML映射文件,或至少从layout.xml文件的参考设置..不要说默认值,无效类型等..我觉得现在好像。 ;-) – 2010-11-18 05:12:53

+0

那么你指定了一个键,我不知道它是否会自动生成一个资源,例如@ pref/font_size或者沿着这些线。这不是一个巨大的交易,我只是想确保我没有失去根本的东西。 – Thomas 2010-11-18 05:14:28