如何保持android中图像按钮的纵横比?
我有 5 个方形 ImageButton,我想将它们并排排列在屏幕底部.我将每一组(不同的 id)设置为:
I have 5 square ImageButtons that I want to have lined up side by side on the bottom of the screen. I have each one set (different id's) as:
<ImageButton
android:id="@+id/box1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:layout_weight="1"
android:layout_margin="1dp"
/>
我在主java中分配了这样的背景:
and I have the background assigned in main java like this:
int[] imageIds = new int[] {R.id.box1,R.id.box2,R.id.box3,R.id.box4,R.id.box5};
for(int i = 0; i<5; i++){
imageButtons[i] = (ImageButton) findViewById(imageIds[i]);
imageButtons[i].setBackgroundResource(R.drawable.blank);
}
我想让它做的是缩放宽度以整齐地并排在屏幕底部(现在可以了),但让高度自动缩放以匹配宽度.这可能吗?我不想使用 setImageSource 因为它会在图像按钮周围放置一个边框.
What I would like to have it do is scale the width to fit neatly side-by-side at the bottom of the screen (which it does now ok), but have the height automatically scale to match the width as well. is this possible? I don't want to use setImageSource because then it puts a border around the imagebutton.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/layoutButtons">
<com.package.SquareButton
android:layout_height="fill_parent"
android:layout_width="0dip"
android:layout_weight="1"
<ImageView
android:id="@+id/box1"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
</com.package.SquareButton>
<com.package.SquareButton
android:layout_height="fill_parent"
android:layout_width="0dip"
android:layout_weight="1"
<ImageView
android:id="@+id/box2"
android:layout_gravity="center"
android:adjustViewBounds="true"
android:scaleType="centerInside"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
</com.package.SquareButton>
.........
</LinearLayout>
然后添加这个自定义按钮类:
And then add this custom button class:
public class SquareButton extends LinearLayout {
public SquareButton(Context context) {
super(context);
}
public SquareButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
// This is used to make square buttons.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}
}