How to properly write XML for AttributeSet?

2019-05-28 19:28发布

I want to create a panel from Misc widgets for Android platform at runtime.

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

What should be the panel_attribute.xml ?

The panel should look like this

<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" />

1条回答
别忘想泡老子
2楼-- · 2019-05-28 20:05

First of all you must define the xml properties in a single file .xml inside the xml folder (subfolder of the resources folder) similarly as you would inside a layout file.

<?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"/>

Secondly retrieving the attribute set is not as easy as two lines of code. You'll need the following function written in Scala. Sorry I am a Scala guy but if you are stuck with java then you can easily convert it!

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*/);
}
查看更多
登录 后发表回答