1

我对 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 中而没有编译或运行时错误,还有其他事情要做吗?

谢谢 !!!

4

3 回答 3

2

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

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

请注意,您需要将类名完全限定为 XML 元素 ( <com.regis.ag.SquareImageButton>),因为您的类不在像android.widget.

于 2013-05-30T09:09:41.140 回答
1

尝试输入您的完整包名:

<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"
       />
于 2013-05-30T09:11:58.580 回答
0

你只需要使用该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"
       />

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

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

于 2013-05-30T09:09:14.470 回答