【问题标题】:Android: Setting button height in XML based on it's widthAndroid:根据宽度在 XML 中设置按钮高度
【发布时间】:2011-04-25 20:57:48
【问题描述】:

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

谢谢你, 乔什

【问题讨论】:

    标签: android xml button android-2.2-froyo


    【解决方案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"

      您可以使用 dipdp

      享受!!

      【讨论】:

        猜你喜欢
        • 2019-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-24
        • 2013-07-17
        • 2015-08-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多