如何为自定义控件定义默认样式?

时间:2013-06-26 14:13:51

标签: android android-custom-view defaults android-custom-attributes android-styles

我有一个自定义控件,它扩展了我自定义属性的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>

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

styles.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 =&lt; ref to a layout&gt;
  • 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);
}

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

0 个答案:

没有答案