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>

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>

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