Android库中复合组件的自定义样式

时间:2012-02-27 20:46:36

标签: android android-widget android-library

我想知道是否有一种方法可以为库中的Android复合控件(窗口小部件)指定和设置样式。

我们已将库中的复合控件移动为可重用的,但是当我们在Android应用程序项目的活动中使用它们时,我们不知道如何指定自定义样式。

我们找到了这个helpful blog来做类似的事情,但它必须将自定义样式指定为应用程序主题,并且我们希望将一种样式直接应用于复合组件。

我尝试了类似的东西,但应用程序崩溃了。

<MyLibraryNameSpace.MyCompoundComponent ...... style="@style/StyleForMyCompoundComponent"> 

1 个答案:

答案 0 :(得分:0)

您可以像对待任何其他视图一样应用样式,就像您在问题中显示一样。碰撞的原因可能与众不同。请记住,默认情况下,复合控件的元素不会应用指定给控件本身的样式。例如,如果您使用包含Button和EditText的FrameLayout创建复合控件,则设置复合控件的背景将尝试应用于FrameLayout(控件的父级持有者),而不是内部元素它(Button和EditText),除非你明确地确定。

如果要为组件添加自定义方法,可以在attrs.xml中执行此操作。例如,假设您要公开属性以修改组件的宽高比:

<?xml version="1.0" encoding="utf-8"?>
<resources>
...

    <declare-styleable name="MyCompoundComponent">
        <attr name="aspectRatio" format="float"/>
    </declare-styleable>

</resources>

然后在自定义控件的构造函数中,您可以获得这些自定义道具的值:

...
public MyCompoundComponent(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    if (attrs == null) return;

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCompoundComponent, defStyleAttr, 0);
    this.aspectRatio = typedArray.getFloat(R.styleable.MyCompoundComponent_aspectRatio, 1);
}

在那里,只要方便,您就可以简单地使用收集属性的值。

相关问题