2012-02-27 37 views
3

我想知道是否有方法可以为库中的Android复合控件(控件)指定和样式。Android库中复合组件的自定义样式

我们已将库中的复合控件移动到可重用的对象中,但我们不知道如何在从android应用程序项目中使用它们时指定自定义样式。

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

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

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

真的,没有答案? – SQLiteNoob 2014-08-05 18:24:54

+0

不,至少两年前,当我需要它时,我没有找到解决方案。 – 2014-08-06 11:29:24

+0

感谢您的回复。当我找到解决方案时,我会记住这篇文章。 – SQLiteNoob 2014-08-07 15:24:50

回答

1

您可以将样式就像你可以做任何其他的看法,就像你表现出对您的问题。碰撞的原因可能是一个不同的原因。请记住,默认情况下,复合控件的元素不会将指定的样式应用于控件本身。例如,如果您使用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); 
} 

一旦出现,只要方便,您就可以简单地使用所收集属性的值。