我可能有点晚了。
然而,通过重写onMeasure()函数可以很容易地实现此行为。
以下是代码示例:
public class MySquareImageButton extends ImageButton {
public MySquareImageButton(Context context) {
super(context);
}
public MySquareImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MySquareImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}
然后,您只需将自己的XML中的ImageButton替换为此自定义组件:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="@+id/txtName"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<com.whatever_your_package.MySquareImageButton
android:id="@+id/btSet"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scaleType="fitEnd"
android:src="@drawable/pin2" />
</LinearLayout>
你只需将wrap_content用于宽度或高度,具体取决于你想要通过哪个参数来确定按钮的大小。
如果你想让按钮的高度根据图像自适应,而宽度则与高度相匹配,那么你可以使用
android:layout_width="wrap_content"
android:layout_height="wrap_content"
同时使用
//(2)if you want the width to match the height
//super.onMeasure(heightMeasureSpec, heightMeasureSpec);