android - 声明可由应用程序修改的库模块的属性

标签 android android-layout

我正在尝试为我的应用程序创建 Android 库模块 (API 21+),它将实现在各种应用程序之间共享的一些业务逻辑。 问题是我想在此库模块中声明属性,为此我将能够在上述项目的应用程序模块中设置值。

有趣的是,我当前的解决方案适用于模拟器,但不适用于物理设备。

这是我现在的方式(简化,省略了不相关的部分):

库的 attrs.xml:

<resources>
    <attr name="lib_Background" format="reference"/>
    <attr name="lib_Logo" format="reference"/>
</resources>

应用程序 styles.xml:

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="lib_Background">@drawable/back</item>
    <item name="lib_Logo">@drawable/logo</item>
 </style>

我是否尝试像这样从库布局的 xml 访问这些资源并不重要:

<ImageView
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:src="?attr/lib_Background"
   android:scaleType="centerCrop"/>

或者像这样编程:

fun Context.getDrawableFromAttributes(idOfAttribute: Int): Drawable? {
    val a = this.theme.obtainStyledAttributes(intArrayOf(idOfAttribute))
    val resourceId = a.getResourceId(0, 0)
    a.recycle()
    return this.resources.getDrawable(resourceId, this.theme)
}

我仍然在模拟器上正确加载了此图像,但在物理设备上为“空”。

有没有更好或正确的方法来实现这一目标?

最佳答案

我有点忘了这个问题。

问题是我对一种特定的密度使用了损坏的 PNG,这导致它为空。所以这根本不是实现错误,这种方法是绝对有效的。

关于android - 声明可由应用程序修改的库模块的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48668411/

相关文章:

android - 以编程方式将边距添加到 RelativeLayout

android - 为什么我会收到此 sqlite 错误?

android - 问题外包RSA加解密

android - 可滚动的 TextView 不允许在应用程序暂停后选择文本

Android - 如何添加简单的页脚?

android - 对早期设备使用 Roboto 字体

android - 将图像定位在形状的右下角

java - 如何在另一个类的微调器中显示值?

android - 允许 Android WebView 的跨源请求

android - 如何使用 Android 通知 API 启用振动和灯光?