arn*_*ouf 11 user-interface android
我在我的应用程序中定义了主题和样式.图标(可绘制)使用样式文件中的引用定义
<attr name="myicon" format="reference" />
Run Code Online (Sandbox Code Playgroud)
和风格一样
<style name="CustomTheme" parent="android:Theme.Holo">
<item name="myicon">@drawable/ajout_produit_light</item>
Run Code Online (Sandbox Code Playgroud)
我需要以编程方式检索drawable以在dialogfragment中使用良好的图像.如果我做的话
mydialog.setIcon(R.style.myicon);
Run Code Online (Sandbox Code Playgroud)
我得到一个id等于0,所以没有图像
我试着用类似的东西
int[] attrs = new int[] { R.drawable.myicon};
TypedArray ta = getActivity().getApplication().getTheme().obtainStyledAttributes(attrs);
Drawable mydrawable = ta.getDrawable(0);
mTxtTitre.setCompoundDrawables(mydrawable, null, null, null);
Run Code Online (Sandbox Code Playgroud)
我试过不同的东西,但结果总是0或null: - /
我怎么能这样做?
arn*_*ouf 18
我找到了在theme和attrs.xml android中定义的Access资源的解决方案
TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {R.attr.homeIcon});
int attributeResourceId = a.getResourceId(0, 0);
Drawable drawable = getResources().getDrawable(attributeResourceId);
Run Code Online (Sandbox Code Playgroud)
Kotlin解决方案:
val typedValue = TypedValue()
context.theme.resolveAttribute(R.attr.yourAttr, typedValue, true)
val imageResId = typedValue.resourceId
val drawable = ContextCompat.getDrawable(contex, imageResId) ?: throw IllegalArgumentException("Cannot load drawable $imageResId")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8176 次 |
| 最近记录: |