Android – 自定义用户界面与自定义属性

我知道可以创build自定义UI元素(通过视图或特定的UI元素扩展)。 但是,是否有可能为新创build的UI元素定义新的属性或属性(我的意思是没有inheritance,但是全新的定义了一些特定的行为,我无法用默认的属性或属性来处理)

例如元素我的自定义元素:

<com.tryout.myCustomElement android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Element..." android:myCustomValue=<someValue> /> 

那么是否可以定义MyCustomValue

谢谢

是。 简短指南:

1.创build一个属性XML

/res/values/attrs.xml创build一个新的XML文件,其属性和types

 <?xml version="1.0" encoding="UTF-8"?> <resources> <declare-styleable name="MyCustomElement"> <attr name="distanceExample" format="dimension"/> </declare-styleable> </resources> 

基本上你必须为你的视图设置一个<declare-styleable /> ,它包含你所有的自定义属性(这里只有一个)。 我从来没有find完整的可能types列表,所以你需要看一个我猜的源代码。 我知道的types是引用(对另一个资源),颜色,布尔值,维度,浮点数,整数和string 。 他们是不言自明的

2.使用布局中的属性

除了一个例外,它的作用方式与上述相同。 您的自定义属性需要它自己的XML名称空间。

 <com.example.yourpackage.MyCustomElement xmlns:customNS="http://schemas.android.com/apk/res/com.example.yourpackage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Element..." customNS:distanceExample="12dp" /> 

非常直截了当。

3.利用你通过的值

修改自定义视图的构造函数以parsing值。

 public MyCustomElement(Context context, AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomElement, 0, 0); try { distanceExample = ta.getDimension(R.styleable.MyCustomElement_distanceExample, 100.0f); } finally { ta.recycle(); } // ... } 

distanceExample是本例中的一个私有成员variables。 TypedArray获得了很多其他东西来parsing其他types的值。

就是这样。 在View使用parsing的值来修改它,例如在onDraw()使用它来相应地改变外观。

在你的res / values文件夹中创buildattr.xml。 在那里你可以定义你的属性:

 <declare-styleable name=""> <attr name="myCustomValue" format="integer/boolean/whatever" /> </declare-styleable> 

当你想在你的布局文件中使用它时,你必须添加

 xmlns:customname="http://schemas.android.com/apk/res/your.package.name" 

然后您可以使用自定义名称的值customname:myCustomValue=""

是的,你可以。只要使用<resource>标签。
喜欢这个:

 <?xml version="1.0" encoding="utf-8"?> <resources> <style name="CodeFont" parent="@android:style/TextAppearance.Medium"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textColor">#00FF00</item> <item name="android:typeface">monospace</item> </style> </resources> 

链接从官方网站