2010-06-22 83 views
2

我正在構建自定義視圖並試圖弄清楚如何將它與eclipse中的GUI佈局編輯器集成。我已將下面的代碼添加到我的構建器中。Android「佈局編輯器」和「自定義屬性」

public baseGrid(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    if (attrs.getAttributeValue(null, "bufferTop") != null) 
    bufferTop = Integer.parseInt(attrs.getAttributeValue(null, "bufferTop")); 
    ... 
從XML佈局文件

和它的作品來閱讀這個XML屬性(... bufferTop="10" ...)。但是,有沒有辦法讓bufferTop在GUI Property Editor中顯示爲一個屬性,我可以在不編輯XML的情況下進行設置?

謝謝

回答

2

嘗試將「attrs.xml」文件添加到「res/values」文件夾中。

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="MyAttrs">  
     <attr name="bufferTop" format="dimension" /> 
     <attr name="myColor" format="color" /> 
     <attr name="myInt" format="integer" />   
     <attr name="myFloat" format="float" /> 
    </declare-styleable>  
</resources> 

閱讀這段代碼:

public baseGrid(Context contxt, AttributeSet attrs) { 
TypedArray a = context.obtainStyledAttributes(attrs, 
       R.styleable.MyAttrs); 
bufferTop = a.getInt(R.styleable.MyAttrs_bufferTop, 10); 
a.recycle(); 
} 

這樣定義窗口小部件:

<?xml version="1.0" encoding="utf-8"?> 
< YOURPACKAGE.BaseGrid 
     android:background="@drawable/red" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     app:bufferTop="100"/> 
+0

謝謝你的回覆。這讓我有90%的途徑。在我的佈局文件中,我必須添加一個名稱空間元素,如下所示。 xmlns:grid =「http://schemas.android.com/apk/res/」 然後,我可以添加一個屬性到XML(... grid:bufferTop =「15dip」 ...)並通過您指定的代碼讀取它。 但是,新的屬性不會顯示在佈局編輯器的GUI部分,除非我先將其手動添加到XML中。一旦我將它添加到XML,它顯示在雜項下。在GUI屬性編輯器中。沒有首先將其添加到XML的情況下沒有辦法讓它出現? – Steve0212 2010-06-22 15:48:43

+0

我試圖跟隨你們,但我認爲我卡在名字空間。你實際使用了什麼<我的包名>?這是完全合格的軟件包名稱嗎? – electrichead 2011-10-06 19:49:36