【发布时间】:2016-04-28 02:11:24
【问题描述】:
所以我有一个 Android library,我希望其他人在使用它时能够轻松自定义它的颜色。问题是颜色不仅仅是一个属性(如视图背景),它更像是一种主题颜色(视图背景、文本颜色、按钮的笔触等......)所以我不能只将它作为视图属性传递。所以我最终使用了color reference 并将其用于样式、布局和可绘制对象:
colors.xml:
<resources>
<attr name="color" format="reference" />
</resources>
layout.xml:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/color">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="?attr/color"/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="@style/LibraryTheme.TextAppearance"/>
</LinearLayout>
库项目中的styles.xml:
<style name="LibraryTheme.TextAppearance">
<item name="android:textColor">?attr/color</item>
<item name="colorControlNormal">?attr/color</item>
<item name="android:textColorHint">?attr/color</item>
<item name="colorControlActivated">?attr/color</item>
<item name="colorControlHighlight">?attr/color</item>
</style>
效果很好,当有人使用我的库时,他必须声明他希望您在他的主题中使用的颜色:
应用项目中的styles.xml:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="color">@color/my_color</item>
</style>
问题是这样的:我想使用默认配色方案提供这个库。现在可以通过 2 个选项执行:
- 使用默认颜色集声明我自己的主题,用户需要从我的主题继承他的主题。
- 在我的 color.xml 中添加一些 default_color,以便用户可以将其用作主题中的颜色。
第一个真的很糟糕,因为我不能强迫用户使用特定的应用程序主题(如 AppCompact.Light)。 第二个也不是很好,因为我希望用户能够无缝地使用默认设置,并且我在主题中有几种颜色需要他设置。
您认为有没有其他方法可以让其他用户轻松使用这些颜色?
谢谢。
【问题讨论】:
-
您可以查看SublimePicker项目的theme设置。这很复杂,因为我必须提供很多主题选项。从你的分类来看,我认为这个设置属于 1。
The first one is really bad, cause I can't force the user to use specific app theme (like AppCopact.Light)--- 不,您会要求用户覆盖 your 主题,例如parent="MyLibrarysDefaultTheme"。没关系。 -
@Vikram 看起来您将所有样式属性用作单个属性,并在代码中设置它们(如
iconColor),如果我在多个地方有颜色,其中一些不能在代码中设置? -
您需要控制设置了哪些属性,以及当它们不存在/无效时该怎么做。只有在创建自定义组件时才能提供此控件。在您的特定情况下,您将检查是否已设置
attr/color,如果没有,请使用默认值 - 在 runtime。您应该记住的另一件事是您的产品的用户(或者更确切地说是客户)将是开发人员,而不是最终用户。如果它不会从库的核心功能中删除任何内容,则可以强加一个要求。
标签: android android-view android-custom-view android-theme android-custom-attributes