Android 以编程方式将 XML 形状设置为可绘制

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10957145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:33:51  来源:igfitidea点击:

Android set XML shape as drawable programmatically

androidxmlresourcesdrawableshape

提问by CQM

Hello I have a drawable myshape.xml, it contains a <shape>and I cannot set an android:id to shapes.

您好,我有一个可绘制的 myshape.xml,它包含一个<shape>并且我无法将 android:id 设置为形状。

In my code I want to set the background of a view to this file using

在我的代码中,我想使用

catAll.setBackgroundDrawable(getResources().getDrawable(R.id......???));

catAll.setBackgroundDrawable(getResources().getDrawable(R.id......???));

where myshape.xml does not show up in my R file because it has no id. and I cannot set id to object.

其中 myshape.xml 没有出现在我的 R 文件中,因为它没有 id。而且我无法将 id 设置为对象。

In my XML I do set the shape by simply typing the drawable resource name. But I need to do this programmatically.

在我的 XML 中,我通过简单地输入可绘制资源名称来设置形状。但我需要以编程方式执行此操作。

回答by K-ballo

You don't need to get the drawable yourself. Use this instead:

您不需要自己获取可绘制对象。改用这个:

catAll.setBackgroundResource(R.drawable.myshape);

For future reference, if you dowish to get the drawable keep in mind that drawables live in the R.drawablenamespace. So your code would became:

为了将来参考,如果您确实希望获得可绘制对象,请记住可绘制对象位于R.drawable命名空间中。所以你的代码会变成:

getResources().getDrawable(R.drawable.myshape);

This is akin to what you do in your XML:

这类似于您在 XML 中所做的:

@drawable/myshape

instead of

代替

@id/myshape