强制Android按钮保持广场

时间:2014-06-04 02:34:17

标签: android image button

我重新打开一个问了两年的问题(是的,我尝试了所有答案,但没有任何快乐)。两年前提出的问题:ImageButton: Force square icon (height = WRAP_CONTENT, width = ?)

我遇到了同样的情况,我试图将Button(带有背景图像)与EditText对齐。以下是我要完成的任务:

Desired outcome

我使用的RelativeLayout是:

<EditText
    android:id="@+id/search_entry"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/search_layout_height"
    android:layout_marginLeft="@dimen/search_layout_left"
    android:padding="@dimen/small_padding"    
    android:background="@drawable/search_box"
    android:inputType="text|number"
    android:textSize="@dimen/small_textsize"
    android:hint="@string/search_for_hint" 
    android:textColorHint="@color/mdgray"
    android:imeOptions="actionSend" />

<Button
    android:id="@+id/search_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@id/search_entry"
    android:layout_alignTop="@id/search_entry"
    android:layout_toRightOf="@id/search_entry"
    android:adjustViewBounds="true"
    android:scaleType="centerInside"
    android:background="@drawable/search_btn" />

然而,我最终得到的是:

Current Outcome

正如你所看到的,它想要横向延伸。

关于如何确保按钮保持正方形的想法?

2 个答案:

答案 0 :(得分:1)

您可以使用ImageButton并创建一个扩展ImageButton的类,该类将覆盖它的onMeasure方法,在那里您可以使用其背景图像的最小大小作为宽度和高度来使背景成为正方形形成一个完美的方形,永远不会使形象变形。

示例:

public class ImageViewPefectSquare extends ImageButton{

public ImageViewPefectSquare(Context context) {
    super(context);
}

public ImageViewPefectSquare(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public ImageViewPefectSquare(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int measuredWidth = getDefaultSize(getSuggestedMinimumWidth(),
            widthMeasureSpec);
    int measuredHeight = getDefaultSize(getSuggestedMinimumHeight(),
            heightMeasureSpec);
    // Ensure this view is always square.
    int min = Math.min(measuredHeight, measuredWidth);
    setMeasuredDimension(min, min);
}
}

它正在做的是它将计算图像的最小尺寸,并将其用作宽度和高度,使其成为一个完美的正方形。

将其用作xml:

<com.youpackage.ImageViewPefectSquare
android:id="@+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/search_entry"
android:layout_alignTop="@id/search_entry"
android:layout_toRightOf="@id/search_entry"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:background="@drawable/search_btn" />

答案 1 :(得分:1)

这是因为如果要保持1:1的宽高比,则需要使用Wrap_content来代替实际值。如果你想让它为所有设备正确扩展,我会在java代码中说明定义屏幕大小并使用它来计算图像的宽度和高度,例如:

button.setWidth(screenWidth/6);
button.setHeight(screenWidth/6);