【问题标题】:Custom View style in a library : use theme attr reference库中的自定义视图样式:使用主题属性参考
【发布时间】:2014-08-20 11:22:41
【问题描述】:

我在中创建了一个自定义View。我希望我的视图背景成为主题属性的参考。比如这样:

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

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

但是在图书馆中,我不想制作自定义主题,因为这会迫使使用该库的人扩展这个令人望而却步的自定义主题。
我希望用户能够设置他使用的任何主题的属性,但这意味着必须在某个地方定义默认值。

那么问题是如何定义默认值,而不制作自定义主题?

【问题讨论】:

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


    【解决方案1】:

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

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多