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

标签 android android-layout

我正在努力为我拥有的应用程序实现一些简单的首选项,并且我正在尝试弄清楚如何使用首选项来操作 XML 文件中定义的 View 。我有一个列表,其中每一行都使用了以下 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:

<?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. 创 build 置屏幕和 Activity
  2. 一旦用户保存设置,让您的支持 PreferenceActivity 将设置保存到文件中(使用 getPreferences(MODE_PRIVATE).edit().putString(PREF_FONT_SIZE, yourSetting).commit()
  3. 在您的主要 Activity #onCreate 中,使用 setContentView 加载布局
  4. 也在那里加载您的首选项
  5. 通过 findViewById 获取 View 并设置从首选项加载的字体大小

关于android - 可以在 XML 布局中访问首选项吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4211408/

相关文章:

android - 为所有屏幕提供图像?

android - 不同 fragment 的多个工具栏布局

java - 空点异常 - ImageLoader

android - 为什么 gradle 说它无法解析 "com.android.support:support-annotations:23.1.1"?

android - 在 android 联系人中导入重复项

Android Webview - 如何捕获被点击的单词?

android - Xamarin:确定 GetSpans() 中的元素是粗体还是斜体?

java - 当用户离线时如何使用自定义无互联网连接可用布局?

java - 在Android中的自定义 View 中设置imageview的大小和位置

java - 尝试在空对象引用上调用虚拟方法 'void android.widget.TextView.append(java.lang.CharSequence)'