Android:根据XML的宽度设置XML格式的按钮高度

时间:2010-10-15 10:17:11

标签: android xml button android-2.2-froyo

我正在研究Android XML中的布局,我想在设置填充父级时设置按钮高度以匹配它的宽度。显然这个数字会根据屏幕大小而改变,所以我不能使用设定的像素大小。有人可以帮助我根据屏幕尺寸获取按钮宽度,然后将其传递到高度设置吗?

谢谢你, 约什

2 个答案:

答案 0 :(得分:3)

我曾经遇到过类似的问题,但没有发现只有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)

答案 1 :(得分:-1)

不使用PX的像素大小,而是提及 dip (即设备无关像素),dip将根据设备屏幕大小独立地以像素为单位。

例如:android:textSize =“12dip”

您可以使用 dip dp

享受!!