[英]How can I create Drawable (or XmlResourceParser object) from XML source code provided as a string?
How can I create Drawable
from XML source code provided as a string ? 如何从以字符串形式提供的 XML源代码创建
Drawable
?
I found the following method: 我发现以下方法:
Drawable drawable = Drawable.createFromXml();
But it requires to provide XmlResourceParser
- and I still don't see a way to create it from XML source code. 但是它需要提供
XmlResourceParser
我仍然看不到从XML源代码创建它的方法。
Sample of the XML source code: XML源代码示例:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<bitmap
android:src="@drawable/icon"
android:gravity="right"
/>
</item>
</layer-list>
FYI FYI
Create a drawable from an XML document using an optional Resources.Theme.
使用可选的Resources.Theme从XML文档创建一个可绘制对象。
Try this 尝试这个
public class RecyclerViewActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view);
Drawable testDrawable;
Resources res = getResources();
try {
testDrawable = Drawable.createFromXml(res, res.getXml(R.xml.test));
} catch (Exception ex) {
Log.e("Error", "Exception creating drawable from XML");
}
}
}
I just think of this, maybe not exactly syntactically correct but I believe this is something you want. 我只是想到了这一点,也许在语法上并不完全正确,但是我相信这是您想要的。
public Drawable xmlStringToDrawable(String yourString){
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader(yourString));
return Drawable.createFromXml(getResources(),parser)
}
This is not an answer to the question. 这不是问题的答案。 But it solved my problem.
但这解决了我的问题。 Thanks everyone for the help:
感谢大家的帮助:
Drawable icon = resources.getDrawable(resources.obtainTypedArray(R.array.arrayName).getResourceId(index, 0), context.getTheme());
BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
bitmapDrawable.setGravity(Gravity.RIGHT);
I generate only index
on run-time in this approach. 我使用这种方法仅在运行时生成
index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.