【问题标题】:Setting attributes of custom views in Android在Android中设置自定义视图的属性
【发布时间】:2011-04-15 05:29:14
【问题描述】:

我有一个扩展按钮的类。我想为其添加一个附加属性。有没有办法从 XML 初始化该属性?例如:

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

【问题讨论】:

    标签: android xml view


    【解决方案1】:

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

    所需的步骤。

    1. 实现您的自定义小部件。
    2. 然后在res/values/中添加文件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>
      

    【讨论】:

    • 如何在 MyButton 类中实际获取 custom:myValue?
    • @GeniaS。请查看我提供的链接。有一个完整的代码示例,在构造函数中从 xml 检索值。
    猜你喜欢
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2019-10-26
    • 1970-01-01
    • 2013-09-01
    相关资源
    最近更新 更多