我正在处理 android XML 中的布局,我想在设置填充父项时设置按钮高度以匹配它的宽度。显然这个数字会根据屏幕大小而变化,所以我不能使用设置的像素大小。有人可以帮助我根据屏幕尺寸获取按钮宽度,然后将其传递给高度设置吗?
谢谢你,乔什
我正在处理 android XML 中的布局,我想在设置填充父项时设置按钮高度以匹配它的宽度。显然这个数字会根据屏幕大小而变化,所以我不能使用设置的像素大小。有人可以帮助我根据屏幕尺寸获取按钮宽度,然后将其传递给高度设置吗?
谢谢你,乔什
我曾经遇到过类似的问题,但没有找到仅适用于 XML 的解决方案。您必须编写自己的 Button-Class 并覆盖 [ onMeassure
][1] 方法。
例子:
/**
* @see android.view.View#measure(int, int)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
}
private int width; // saves the meassured width
/**
* Determines the width of this view
*
* @param measureSpec
* A measureSpec packed into an int
* @return The width of the view, honoring constraints from measureSpec
*/
private int measureWidth(int measureSpec) {
int result = 30;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
result =1123; // meassure your with here somehow
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by measureSpec
result = Math.min(result, specSize);
}
}
width = result;
return result;
}
/**
* Determines the height of this view
*
* @param measureSpec
* A measureSpec packed into an int
* @return The height of the view, honoring constraints from measureSpec
*/
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
result = width;
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by measureSpec
result = Math.min(result, specSize);
}
}
return result;
}
[1]: http: //developer.android.com/reference/android/view/View.html#onMeasure (int , int)
代替PX使用Pixel size,提到dip(即设备独立像素),dip会根据设备屏幕大小独立取像素大小。
例如:android:textSize="12dip"
您可以使用dip或dp。
享受!!