如何:为自定义窗口小部件定义主题(样式)项

jsm*_*ith 81 android android-theme

我为我们在整个应用程序中广泛使用的控件编写了一个自定义小部件.widget类ImageButton以几种简单的方式派生和扩展它.我已经定义了一个可以应用于小部件的样式,但是我更喜欢通过主题来设置它.在R.styleable我看到小部件样式属性,如imageButtonStyletextViewStyle.有没有办法为我写的自定义小部件创建类似的东西?

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命名约定.

  • 关于这一切最令人惊奇的是,Google的某些人认为这没关系. (26认同)
  • 有没有办法在不使用主题的情况下做同样的事情?我有一些自定义小部件,但我希望用户能够使用他们想要的任何主题的这些小部件.按照您发布的方式进行操作会要求用户使用我的主题. (4认同)
  • @theDazzler:如果您指的是开发人员可以使用的库,那么他们将能够创建自己的主题并使用主题中的style属性指定窗口小部件的样式(在此答案中为`customImageButtonStyle`).这就是Android上自定义操作栏的方式.如果您的意思是在运行时更改主题,那么这种方法是不可能的. (3认同)