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

4
我想知道是否有一种方法可以在库中指定和为Android复合控件(小部件)设置样式。
我们已经将复合控件移动到库中以便重用,但是我们不知道如何在从android应用程序项目中使用它们时指定自定义样式。
我们找到了这个有用的博客,可以做类似的事情,但必须将自定义样式指定为应用程序主题,而我们希望直接将一个样式应用于复合组件。
我尝试过像这样的东西,但应用程序崩溃了。
<MyLibraryNameSpace.MyCompoundComponent ...... style="@style/StyleForMyCompoundComponent"> 

不,至少在两年前当我需要它时,我没有找到解决方案。 - Marc Cals
谢谢回复。如果我找到解决方案,我会记住这篇帖子。 - SQLiteNoob
1个回答

0

您可以像对待其他视图一样应用样式,就像您在问题中展示的那样。可能崩溃的原因是另一个原因。请记住,复合控件的元素默认情况下不会应用到控件本身指定的样式。例如,如果您使用FrameLayout包含Button和EditText创建复合控件,则设置复合控件的背景将尝试应用于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);
}

一旦到达那里,您可以在方便的时候简单地使用收集属性的值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接