安卓ImageView控件只能设置一个宽度,但可以通过以下几种方式实现两个宽度的效果:
public class CustomImageView extends ImageView {
private int width1;
private int width2;
public CustomImageView(Context context) {
super(context);
}
public CustomImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setWidth1(int width1) {
this.width1 = width1;
requestLayout();
}
public void setWidth2(int width2) {
this.width2 = width2;
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int width;
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
width = Math.min(width1, width2);
if (widthMode == MeasureSpec.AT_MOST) {
width = Math.min(width, widthSize);
}
}
setMeasuredDimension(width, heightMeasureSpec);
}
}
然后在布局文件中使用自定义的ImageView控件。
以上是三种实现安卓ImageView两个宽度的方法,选择其中一种适合你的需求进行使用。