【问题标题】:Custom style for a Compound Component in Android LibraryAndroid 库中复合组件的自定义样式
【发布时间】:2012-02-27 20:46:35
【问题描述】:

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

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

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

我尝试过类似的方法,但应用程序崩溃了。

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

【问题讨论】:

  • 不,至少两年前我需要它时,我没有找到解决方案。
  • 感谢您的回复。如果/当我找到解决方案时,我会记住这篇文章。

标签: android android-widget android-library


【解决方案1】:

您可以像在任何其他视图中一样应用样式,就像您在问题中显示的那样。坠机的原因可能是另一个原因。请记住,复合控件的元素默认情况下不会将指定的样式应用于控件本身。例如,如果您使用 FrameLayout 和 EditText 创建复合控件,则设置复合控件的背景将尝试应用于 FrameLayout(控件的父持有者),而不是内部的元素除非您明确确定它(按钮和 EditText)。

如果您想为您的组件添加自定义方法,您可以在 attrs.xml 中进行。例如,假设您想公开一个属性来修改组件的纵横比:

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

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

</resources>

然后在你自定义控件的构造函数中就可以获取这些自定义props的值了:

...
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);
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多