jsm*_*ith 81 android android-theme
我为我们在整个应用程序中广泛使用的控件编写了一个自定义小部件.widget类ImageButton以几种简单的方式派生和扩展它.我已经定义了一个可以应用于小部件的样式,但是我更喜欢通过主题来设置它.在R.styleable我看到小部件样式属性,如imageButtonStyle和textViewStyle.有没有办法为我写的自定义小部件创建类似的东西?
Mic*_*ael 206
是的,有一种方法:
假设您有一个窗口小部件属性声明(in attrs.xml):
<declare-styleable name="CustomImageButton">
<attr name="customAttr" format="string"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
声明将用于样式引用的属性(in attrs.xml):
<declare-styleable name="CustomTheme">
<attr name="customImageButtonStyle" format="reference"/>
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)
为窗口小部件声明一组默认属性值(in styles.xml):
<style name="Widget.ImageButton.Custom" parent="android:style/Widget.ImageButton">
<item name="customAttr">some value</item>
</style>
Run Code Online (Sandbox Code Playgroud)
声明自定义主题(in themes.xml):
<style name="Theme.Custom" parent="@android:style/Theme">
<item name="customImageButtonStyle">@style/Widget.ImageButton.Custom</item>
</style>
Run Code Online (Sandbox Code Playgroud)
使用此属性作为窗口小部件构造函数(in CustomImageButton.java)中的第三个参数:
public class CustomImageButton extends ImageButton {
private String customAttr;
public CustomImageButton( Context context ) {
this( context, null );
}
public CustomImageButton( Context context, AttributeSet attrs ) {
this( context, attrs, R.attr.customImageButtonStyle );
}
public CustomImageButton( Context context, AttributeSet attrs,
int defStyle ) {
super( context, attrs, defStyle );
final TypedArray array = context.obtainStyledAttributes( attrs,
R.styleable.CustomImageButton, defStyle,
R.style.Widget_ImageButton_Custom ); // see below
this.customAttr =
array.getString( R.styleable.CustomImageButton_customAttr, "" );
array.recycle();
}
}
Run Code Online (Sandbox Code Playgroud)
现在您必须应用于Theme.Custom所有使用的活动CustomImageButton(在AndroidManifest.xml中):
<activity android:name=".MyActivity" android:theme="@style/Theme.Custom"/>
Run Code Online (Sandbox Code Playgroud)
就这样.现在CustomImageButton尝试从customImageButtonStyle当前主题的属性加载默认属性值.如果在主题或属性的值中找不到这样的属性@null,obtainStyledAttributes则将使用最终参数:Widget.ImageButton.Custom在这种情况下.
您可以更改所有实例和所有文件的名称(除外AndroidManifest.xml),但最好使用Android命名约定.
| 归档时间: |
|
| 查看次数: |
39783 次 |
| 最近记录: |