-->

如何正确地编写XML为AttributeSet中的?(How to properly write X

2019-09-22 16:24发布

我想创建从面板其它部件的Android平台在运行时。

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

Answer 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编写下面的函数。 对不起,我是一个斯卡拉的人,但如果你坚持使用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*/);
}


文章来源: How to properly write XML for AttributeSet?