【问题标题】:Attach Extra data to ImageButton in android将额外数据附加到android中的ImageButton
【发布时间】:2012-02-12 21:51:52
【问题描述】:

我想在xml资源文件的ImageButton中添加一些额外的数据,并能够通过代码读取它

就这样

<ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            app:angle="0"
            app:titletext="imageButton1"/>

我在哪里可以将这些数据定义为可访问且不会导致 XML 错误

提前致谢

【问题讨论】:

    标签: android android-resources


    【解决方案1】:

    我认为这在 Android SDK 中是不可能的。因为ImageButton元素需要预定义。

    你需要定义什么样的数据,为什么要在xml中定义? strings.xml不够吗?

    【讨论】:

    • 每个按钮都会改变 textview 的文本,我有很多按钮,所以我想定义一个额外的属性并将其附加到按钮上以便能够通过代码获取它
    • erm 每个按钮都已经有这个... android:id="@+id/imageButton1" 所以 id 是:"imageButton1"?您可以在代码 ImageButton myButton = (ImageButton) findViewById(R.id.imageButton1); 中访问它
    【解决方案2】:

    在 Android 中有一种定义的方式来做到这一点,即在 XML 中定义自己的命名空间,然后通过读取创建对象时传入的属性来读取代码中的值。

    我不打算详细讨论这个问题,因为这个问题之前已经提出过,并且有很多关于它的好文章。

    您可能想阅读以下文章:

    【讨论】:

      【解决方案3】:

      您可以将其子类化并拥有自己的数据字段,而不是在 ImageButton 中寻找隐藏数据,如果您仍想使用 ImageButton,请为其提供一个包装类,其中包含一个 ImageButton 作为字段变量,如下所示:-

      class ButtonWrapper{
         ImageButton button;
         int app_angle=0;
         String app_titletext="imageButton1"
      }
      

      【讨论】:

      • 这很好,但是在我声明自己的按钮包装器之后,我可以使用这种新类型在 main.xml 文件中声明 UI 元素吗?如果是的话怎么做?
      • 类按钮包装器只是一个包装器,您可以使用实际的ImageButton,而不是使用ImageButton 的对象,您可以使用buttonWrapper(object of wrapper).button 来访问按钮。如果你想设置字段 app_angle,你可以使用 app_angle=10 或者如果你喜欢封装,你可以使用 setter。为此只有一种使用 XML 的方法,即创建您自己的自定义 ImageButton,这不值得额外的代码,因为您只想拥有一些额外的字段。
      猜你喜欢
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2013-10-04
      • 2017-01-09
      • 1970-01-01
      • 2016-12-10
      • 2017-10-26
      • 1970-01-01
      相关资源
      最近更新 更多