无法在图像按钮中设置背景

时间:2015-10-27 16:52:47

标签: android background android-imagebutton

我有一个ImageButton

  <com.defcomdevs.invento16.SquareImageView
    android:id="@+id/picture"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal|top"
    android:background="@drawable/custom_button"
    android:layout_margin="1dp"
    android:scaleType="fitCenter" />

SquareImageView是一个扩展Imagebutton的类,它根据屏幕大小自动设置宽度和高度。

custom_button.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false">
    <shape android:shape="rectangle">
        <stroke android:width="5dp" android:color="#885599"/>
    </shape>
</item>
<item android:state_pressed="true">
    <shape android:shape="rectangle">
        <stroke android:width="8dp" android:color="#802196f3"/>
        <gradient android:startColor="#802196f3" android:endColor="#802196f3"/>
    </shape>
</item>

我的问题是当我将背景设置为custom_button时,我以编程方式设置的图像与按钮的整个区域重叠。不显示背景。否则图像完美地设置在按钮内。 有点像这样:

enter image description here

正如您所看到的那样是background = custom_button。

enter image description here

否则就是这种情况。 现在我不想要任何这些。 我想要的是,将custom_button设置为ImageButton的背景,将src设置为该图像,如图所示。怎么样?请帮忙。谢谢。

SquareImageView.class

package com.defcomdevs.invento16;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.ImageButton;

public class SquareImageView extends ImageButton {

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

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

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

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
}
}

0 个答案:

没有答案
相关问题