猿问

如何从以字符串形式提供的 XML 源代码创建 Drawable

如何Drawable从以字符串形式提供的XML 源代码创建?


我找到了以下方法:


Drawable drawable = Drawable.createFromXml();

但是它需要提供XmlResourceParser- 我仍然没有看到从 XML 源代码创建它的方法。


XML 源代码示例:


<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <bitmap

            android:src="@drawable/icon"

            android:gravity="right"

            />

    </item>

</layer-list>


慕村225694
浏览 220回答 3
3回答

慕容708150

我只是想到这一点,也许在语法上并不完全正确,但我相信这是您想要的。public Drawable xmlStringToDrawable(String yourString){&nbsp; &nbsp; &nbsp;XmlPullParser parser = Xml.newPullParser();&nbsp; &nbsp; &nbsp;parser.setInput(new StringReader(yourString));&nbsp; &nbsp; &nbsp;return Drawable.createFromXml(getResources(),parser)}

梵蒂冈之花

这不是问题的答案。但它解决了我的问题。感谢大家的帮助:&nbsp; &nbsp; &nbsp; &nbsp; Drawable icon = resources.getDrawable(resources.obtainTypedArray(R.array.arrayName).getResourceId(index, 0), context.getTheme());&nbsp; &nbsp; &nbsp; &nbsp; BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;&nbsp; &nbsp; &nbsp; &nbsp; bitmapDrawable.setGravity(Gravity.RIGHT);index在这种方法中,我只在运行时生成。

慕侠2389804

供参考createFromXml()使用可选的 Resources.Theme从XML 文档创建可绘制对象。试试这个public class RecyclerViewActivity extends AppCompatActivity {&nbsp; &nbsp; @Override&nbsp; &nbsp; protected void onCreate(Bundle savedInstanceState) {&nbsp; &nbsp; &nbsp; &nbsp; super.onCreate(savedInstanceState);&nbsp; &nbsp; &nbsp; &nbsp; setContentView(R.layout.activity_recycler_view);&nbsp; &nbsp; &nbsp; &nbsp; Drawable testDrawable;&nbsp; &nbsp; &nbsp; &nbsp; Resources res = getResources();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; testDrawable = Drawable.createFromXml(res, res.getXml(R.xml.test));&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception ex) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.e("Error", "Exception creating drawable from XML");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答