way*_*ord 5 android android-custom-view
我试图在android上创建一个自定义复合视图(从relativelayout子类),并尝试指定默认样式.我可以做到这一点,但我想知道defStyleAttr参数用于什么,以及如何使用它.
我遇到了这个方法context.obtainStyledAttributes(AttributeSet set,int [] attrs,int defStyleAttr,int defStyleRes).
我明白那个:
AttributeSet set 如果从XML膨胀,我将从视图的构造函数中获取, int[] attrs 将是我可能创建的任何自定义视图字段的关键值, int defStyleRes 将是我可以提供的默认样式,它被定义为样式资源.但是,我无法弄清楚如何使用int defStyleAttr参数.我已经阅读了文档并提供了这样的attr资源:
<declare-styleable name="BMTheme">
<attr name="BMButtonStyle" format="reference" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
然后在我的主题资源文件中我有这个:
<style name="Theme.Custom" parent="@android:style/Theme">
<item name="BMButtonStyle">@style/BMButton</item>
</style>
Run Code Online (Sandbox Code Playgroud)
反过来引用这种风格:
<style name="BMButton">
<item name="text">some string</item>
<item name="android:paddingLeft">10dp</item>
<item name="android:paddingRight">10dp</item>
</style>
Run Code Online (Sandbox Code Playgroud)
在代码中,当我传入0 for defStyleAttr和样式资源id时defStyleRes,我成功获得了我在BMButton样式中定义的默认值:
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RightArrowButton, 0, R.style.BMButton);
Run Code Online (Sandbox Code Playgroud)
但是当我传入BMButtonStyle的attr资源id(后面又引用BMButton样式)时,为defStyleAttr0 defStyleRes然后我没有得到我在样式中指定的值.
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RightArrowButton, R.attr.BMButtonStyle, 0);
Run Code Online (Sandbox Code Playgroud)
如果我defStyleAttr以错误的方式使用参数,请告诉我,如果有人知道,为什么只需要a defStyleAttr和defStyleRes参数就需要a 和参数defStyleRes?
我在阅读这篇文章后想出了我的错误: 使用自定义属性创建默认样式
基本上,为了使用defStyleAttr参数,我的项目需要在清单中设置我的自定义主题定义主题.
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.Custom" >
Run Code Online (Sandbox Code Playgroud)