库中的自定义视图样式:使用主题attr参考

时间:2014-08-20 11:22:42

标签: android android-view android-theme android-styles

我在中制作了自定义View。我希望我的视图背景是主题属性的引用。例如:

<style name="MyView">
    <item name="android:background">?attr/my_view_background</item>
</style>

Android模式在多个地方使用此模式,例如列表分隔符。

但是在图书馆里,我不想制作一个自定义主题,因为这会强迫某人使用lib来扩展这个自定义主题,这个主题很难找到。
我希望用户能够设置属性,无论他使用什么主题,但这意味着某处必须定义默认值。

所以问题是如何在不制作自定义主题的情况下定义默认值?

1 个答案:

答案 0 :(得分:0)

以下是如何制作它:在Context.obtainStyledAttributes(int, int[], int, int)构造函数中使用MyView的第三个参数:

public MyView(AttributeSet attrs, int defStyle) {

    TypedArray backgroundArray = getContext().obtainStyledAttributes(
        attrs,                                    // The attrs passed to the view
        new int[] { android.R.attr.background },  // I'm only interrested in getting the background
        R.attr.myViewBackground,                  // The user can pass a custom background using this theme attribute
        theme R.style.MyView                      // And that's the default style
    );
    setBackgroundDrawable(backgroundArray.getDrawable(0)); // At 0, there's the background attribute
    backgroundArray.recycle();
}
相关问题