2010-06-22 82 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