android - 如何从库项目中引用应用程序主题属性?

标签 android android-ui android-theme android-library android-styles

我正在构建一个库,并希望它尽可能通用。

因此,我想将 TextViewtextColor 属性设置为使用我的库的应用指定为其 primaryColor 的任何值.

使用 android:textColor="?colorPrimary" 似乎给我一种随机颜色,而不是我的测试应用程序中指定的颜色。这可能是因为它试图在库的 R.java 文件中查找该资源 ID,而不是询问应用程序?

那么是否有可能在库范围之外引用颜色?我知道我可以通过引入自定义属性来解决这个问题,但我想避免使用该解决方案,因为它需要库的用户更新他们的应用主题,而且它不会开箱即用。

最佳答案

供将来引用:

我找不到基于 XML 的解决方案,但您可以做的是在运行时以编程方式读出主题属性并从 Java 应用它们。

这就是我为 Android-MaterialPreference 所做的该库除了读取应用程序的 colorAccent 属性外,还会查找可选的自定义 mp_colorAccent 属性,该属性可以覆盖默认颜色。评论应该足够清楚。

package com.jenzz.materialpreference;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.Resources.Theme;
import android.content.res.TypedArray;

import static android.graphics.Color.parseColor;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.LOLLIPOP;

final class ThemeUtils {

  // material_deep_teal_500
  static final int FALLBACK_COLOR = parseColor("#009688");

  private ThemeUtils() {
    // no instances
  }

  static boolean isAtLeastL() {
    return SDK_INT >= LOLLIPOP;
  }

  @TargetApi(LOLLIPOP)
  static int resolveAccentColor(Context context) {
    Theme theme = context.getTheme();

    // on Lollipop, grab system colorAccent attribute
    // pre-Lollipop, grab AppCompat colorAccent attribute
    // finally, check for custom mp_colorAccent attribute
    int attr = isAtLeastL() ? android.R.attr.colorAccent : R.attr.colorAccent;
    TypedArray typedArray = theme.obtainStyledAttributes(new int[] { attr, R.attr.mp_colorAccent });

    int accentColor = typedArray.getColor(0, FALLBACK_COLOR);
    accentColor = typedArray.getColor(1, accentColor);
    typedArray.recycle();

    return accentColor;
  }

}

关于android - 如何从库项目中引用应用程序主题属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121068/

相关文章:

Android - 用于 onDraw 的预绘制 Canvas

android - 有没有更快的方法来转储 UI 层次结构?

android - 如何将 NavigationView 与标准 Android 主题一起使用?

android - 在 Android Studio 中导入图像作为背景

Android ListView ScrollView 从蓝色改变边缘发光颜色

android - ?attr/在Android上是什么意思?

java - 在java中将字节数组转换为字符串

android - 使用 Facebook Android SDK 分享 Facebook 页面的帖子

Android 图像缓存

java - ScrollView 没有滚动到 ViewFlipper 的顶部