【问题标题】:Android/Java: how to define a specific class usable in an xml layout file?Android/Java:如何定义可在 xml 布局文件中使用的特定类?
【发布时间】:2013-05-25 18:48:20
【问题描述】:

我对 Android SDK 提供的默认 ImageButton 项不满意,我想定义我自己的 ImageButton(我们称之为 SquareImageButton),它从 ImageButton 扩展而来。

我因此创建了一个这样的类:

public class SquareImageButton extends ImageButton {

// Here I want to include some code which would for example
// force the width of the SquareImageButton to be equal to its height
// And many other things !!!

}

现在我想在 xml 中使用这个 SquareImageButton,就像我使用普通的 ImageButton 一样。比如这样:

<SquareImageButton
            android:id="@+id/speakButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@drawable/icon_rounded_no_shadow_144px"
           />

我应该如何在我的 SquareImageButton 类中编写来做到这一点?为了能够将我的 SquareImageButton 包含在我的 xml 中而没有编译或运行时错误,还有其他事情要做吗?

谢谢!!!

【问题讨论】:

  • 你必须添加包名:

标签: java android xml eclipse layout


【解决方案1】:

您只需使用class 属性即可。

      <Button
        class="com.example.SquareImageButton" 
        android:id="@+id/speakButton"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:src="@drawable/icon_rounded_no_shadow_144px"
       />

您可以使用 Activity 中的 findById 方法找到它,例如任何内置元素。

至于类:你只需要覆盖派生类中的所有抽象方法/构造函数。

【讨论】:

    【解决方案2】:

    我应该如何在我的 SquareImageButton 类中编写来做到这一点?

    我会覆盖ImageButton 提供的所有构造函数,尤其是ImageButton(Context context, AttributeSet attrs),因为这应该是布局膨胀使用的构造函数。确保类和这些构造函数是public。这应该就是你所需要的。

    请注意,您需要将类名完全限定为 XML 元素 (&lt;com.regis.ag.SquareImageButton&gt;),因为您的类不在像 android.widget 这样的知名包中。

    【讨论】:

    • 我向构造函数和适配器类公开。谢谢
    【解决方案3】:

    尝试输入您的完整包名:

    <com.your.package.name.SquareImageButton
            android:id="@+id/speakButton"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@drawable/icon_rounded_no_shadow_144px"
           />
    

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2012-06-07
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多