3

我有一个自定义控件,它扩展了我有自定义属性的DialogPreference,我想为它们定义默认值。

这是我attrs.xml的相关部分:

<!-- definition of my custom attributes -->
<declare-styleable name="MyPreference">
    <attr name="myAttr1" format="string" />
    <attr name="myAttr2" format="reference" />
</declare-styleable>
<!-- declatation of my style for my AppTheme -->
<declare-styleable name="AppTheme">
    <attr name="myPreferenceStyle" format="reference" />
</declare-styleable>

主题.xml

<style name="AppTheme" parent="@style/Theme.Sherlock.Light.DarkActionBar">
    <!-- try of replacing the default text color -->
    <item name="android:textAppearance">@style/WhiteText</item>
    <item name="myPreferenceStyle">@style/Preference.My</item>
</style>

样式.xml

<style name="WhiteText" parent="@android:style/TextAppearance">
    <!-- set the default color to white... however it doesn't work -->
    <item name="android:textColor">#fff</item>
</style>

<style name="Preference">
    <item name="android:positiveButtonText">@android:string/ok</item>
    <item name="android:negativeButtonText">@android:string/cancel</item>
</style>

<style name="Preference.My">
    <item name="android:dialogLayout">@layout/preferences_my_picker</item>
    <item name="myAttr1">@string/unknown</item>
    <item name="myAttr2">@array/bits</item>
</style>

所以我已经定义了我希望 MyPreference 类应该有这样的默认值:

  • android:positiveButtonText = "OK"
  • android:negativeButtonText = "取消"
  • android:dialogLayout = <引用布局>
  • myAttr1 = "未知"
  • myAttr2 = [1, 2, 4]

但是当我尝试访问它们时,我什么也得不到:

public MyPreference(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyPreference, defStyle, 0);

    String txt = a.getText(R.styleable.MyPreference_myAttr1);
    // txt == null :(

    int bitsResId = a.getResourceId(R.styleable.MyPreference_myAttr2, -1);
    // next line will crash bitsResId == -1
    int[] bits = res.getIntArray(bitsResId);

    a.recycle();
}

public MyPreference(Context context, AttributeSet attrs) {
    this(context, attrs, R.attr.myPreferenceStyle);
}

如果有人能解释我做错了什么,我会非常有帮助。还有为什么我不能将默认文本颜色更改为白色。

4

0 回答 0