【问题标题】:How to properly write XML for AttributeSet?如何为 AttributeSet 正确编写 XML?
【发布时间】:2012-09-20 07:54:37
【问题描述】:

我想在运行时从Misc widgets for Android platform 创建一个面板。

 XmlPullParser parser = getResources().getXml(R.xml.panel_attribute);
 AttributeSet attributes = Xml.asAttributeSet(parser);
 Panel panel = (Panel) new Panel(getActivity(),attributes);

panel_attribute.xml 应该是什么?

面板应该是这样的

<org.miscwidgets.widget.Panel
    xmlns:panel="http://schemas.android.com/apk/res/org.miscwidgets"
    android:id="@+id/topPanel"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dip"
    panel:animationDuration="1000"
    panel:closedHandle="@drawable/sliding_drawer_handle_minimized"
    panel:content="@+id/searchparams_layout"
    panel:handle="@+id/handle"
    panel:linearFlying="true"
    panel:openedHandle="@drawable/sliding_drawer_handle_minimized"
    panel:position="top" />

【问题讨论】:

    标签: android xmlpullparser


    【解决方案1】:

    首先,您必须在 xml 文件夹(资源文件夹的子文件夹)内的单个文件 .xml 中定义 xml 属性,就像在布局文件中一样。

    <?xml version="1.0" encoding="utf-8"?>
    <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
        android:contentDescription="@string/no_descr"
        android:src="@drawable/dummy"/>
    

    第二次检索属性集并不像两行代码那么简单。您需要以下用 Scala 编写的函数。对不起,我是一个 Scala 人,但如果你被 java 卡住了,那么你可以轻松地转换它!

    def getAttributeSetFromXml(xmlId: Int, tagName: String, resources: Resources): AttributeSet = {
    /**
     * The good thing for being an internal function is that we don't need to pass tagName as a ref
     */
    def getAttributeSet(xmlPullParser: XmlPullParser /*, tagName: String*/): AttributeSet = {
      val state = xmlPullParser.next();
      if (state == XmlPullParser.START_TAG &&
        (xmlPullParser.getName contains tagName)) {
        Xml.asAttributeSet(xmlPullParser);
      }
      else {
        if (state == XmlPullParser.END_DOCUMENT) null;
        else getAttributeSet(xmlPullParser /*, tagName*/);
      }
    }
    
    getAttributeSet(resources.getXml(xmlId) /*, tagName*/);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 2011-03-17
      • 2013-02-06
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多