2012-09-20 34 views
2

我想在運行時從Misc widgets for Android platform創建一個面板。如何爲AttributeSet正確編寫XML?

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

回答

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*/); 
}