小部件宽高比1:1(方形)

时间:2014-05-28 18:42:25

标签: android android-layout widget android-linearlayout

我需要将小部件宽高比设为1:1 - 更确切地说,它必须是方形的。

我的布局如下:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/backgroundImage"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="false"
    android:focusable="false"
    android:scaleType="fitXY"
    android:src="@drawable/rounded_conners" />

<ImageButton
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:adjustViewBounds="true"
    android:background="@drawable/transparent_color"
    android:clickable="true"
    android:focusable="true"
    android:padding="8dp"
    android:scaleType="fitCenter"
    android:src="@drawable/btn03_off" />

</FrameLayout>

我以编程方式更改ImageView的形状,因此它必须是ImageView。在背景中是形状背景,其顶部是ImageButton。

我试图让我自己的SquareLayout从LinearLayout扩展,但似乎Android小部件只显示LinearLayout而不是他的扩展版本我覆盖了onMeasure(meethod)

public class SqueareLinearLayout extends LinearLayout {
public SqueareLinearLayout(Context context) {
    super(context);
}

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


@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height = MeasureSpec.getSize(heightMeasureSpec);
    int size = width > height ? height : width;
    setMeasuredDimension(size, size);
}

}

有人知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

所以看来我终于解决了我的问题..

在我的布局中,我只使用了一个ImageButton:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:background="@drawable/transparent_color"
        android:clickable="true"
        android:focusable="true"
        android:padding="8dp"
        android:scaleType="fitCenter"
        android:src="@drawable/btn03_off" />
</FrameLayout>

当我想改变我的背景形状(不是src图像资源,它位于顶部)时,我只是打电话:

views.setInt(R.id.button, "setBackgroundResource", R.drawable.rounded_conners);

因此窗口小部件具有与图像相同的纵横比。