2011-04-15 48 views
2

我有一个扩展按钮的类。我想添加一个额外的属性。有没有办法从XML初始化该属性?例如:在Android中设置自定义视图的属性

<MyButton android:id="@+id/myBtn" myValue="Hello World"></MyButton> 

public class MyButton extends Button{ 
private String myValue = ""; 

public CalcButton(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
} 
} 

回答

1

是。您可以拥有自定义属性并为其分配值。您甚至可以分配方法来处理小部件上的自定义事件。 Long press definition at XML layout, like android:onClick does

需要的步骤。

  1. 实现您的自定义小部件。
  2. 然后在RES /价值/添加文件attrs.xml有以下内容:

    <xml version="1.0" encoding="utf-8"?> 
    <resources> 
        <declare-styleable name="MyButton"> 
         <attr name="myValue" format="string"/> 
        </declare-styleable> 
    </resources> 
    
  3. 在myButton的构造XML检索值。记得实现所有的构造函数,而不仅仅是一个。
  4. 使用你的布局XML的新属性:

    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android" 
        xmlns:custom="http://schemas.android.com/apk/res/**your.package**" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:orientation="vertical" 
        > 
    
        <your.package.MyButton 
         android:id="@+id/theId" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         custom:myValue="myDoSomething" 
        /> 
        <!-- Other stuff --> 
    </LinearLayout> 
    
+0

你怎么竟获取自定义:用作MyButton类中myvalue的? – 2013-09-05 22:43:13

+0

@GeniaS。请查看我提供的链接。有一个完整的代码示例,从构造函数中的xml中检索valuse。 – 2013-09-14 09:50:42

相关问题