Android:根据宽度在 XML 中设置按钮高度
Posted
技术标签:
【中文标题】Android:根据宽度在 XML 中设置按钮高度【英文标题】:Android: Setting button height in XML based on it's width 【发布时间】:2011-04-25 20:57:48 【问题描述】:我正在处理 android XML 中的布局,我想在其中设置按钮高度以在设置填充父项时匹配它的宽度。显然这个数字会根据屏幕大小而变化,所以我不能使用设置的像素大小。有人可以帮我根据屏幕尺寸获取按钮宽度,然后将其传递给高度设置吗?
谢谢你, 乔什
【问题讨论】:
【参考方案1】:我曾经遇到过类似的问题,但没有找到仅适用于 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,整数)
【讨论】:
【参考方案2】:不使用PX的Pixel size,而是提到dip(即设备独立像素),dip会根据设备屏幕尺寸独立采用像素大小。
例如:android:textSize="12dip"
您可以使用 dip 或 dp。
享受!!
【讨论】:
以上是关于Android:根据宽度在 XML 中设置按钮高度的主要内容,如果未能解决你的问题,请参考以下文章
如何在xml中设置复合可绘制文本视图的高度和宽度? [关闭]
如何在 CollectionView.Footer 中设置 XAML 按钮大小?