在安卓中调整布局的动态尺寸

5
在一个包含许多组件的Activity中,我有一个RelativeLayout容器,其中包含一个WebView(它只显示一个我不知道大小的TextView)。
以下是XML代码:
<RelativeLayout android:id="@+id/descripcionRelative" android:layout_below="@+id/descripcion_bold" android:layout_width="match_parent" android:layout_height="125dip" android:background="@drawable/my_border">
    <WebView android:id="@+id/webViewDescripcion" android:layout_width="wrap_content" android:layout_height="wrap_content"/>      
</RelativeLayout>

RelativeLayout的属性android:layout_height为125dip,这是因为如果文字太长,我想将其限制在125dip内。如果文字很大,我会看到带有滚动条的文本。太好了!
但是...如果文字很短,我会看到很多不必要的空间。
其中一个解决方案是将RelativeLayout的android:layout_height更改为wrap_content。如果文字很短,该组件将具有确切的像素,但如果文字太长,我无法将其限制。
最大的问题是我无法计算WebView的高度。如果我执行:descripcion_web.getHeight(),它会返回0。
如果我在此处调用此方法,它不会返回正确的数字:
descripcion_web.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            RelativeLayout marco = (RelativeLayout)findViewById(R.id.descripcionRelative);
            System.out.println("Height webView: "+webView.getHeight());   
            System.out.println("Height relative: "+marco.getHeight());            
        }           
    });

我尝试在onResume()方法中调用它,但是它没有起作用。
另一种解决问题的尝试是将android:layout_height设置为match_parent,并使用View方法setMaximumHeight(),但它不存在。然而,setMinimumHeight()是存在的...
我该如何解决这个问题?非常感谢!
1个回答

7

遗憾的是,大多数Android视图没有"setMaximumHeight"功能。但您可以通过继承WebView来实现此功能。以下是一个示例,演示如何实现:

package com.am.samples.maxheight;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;

public class CustomWebView extends WebView {

    private int maxHeightPixels = -1;

    public CustomWebView(Context context, AttributeSet attrs, int defStyle,
            boolean privateBrowsing) {
        super(context, attrs, defStyle, privateBrowsing);
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomWebView(Context context) {
        super(context);
    }

    public void setMaxHeight(int pixels) {
        maxHeightPixels = pixels;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (maxHeightPixels > -1 && getMeasuredHeight() > maxHeightPixels) {
            setMeasuredDimension(getMeasuredWidth(), maxHeightPixels);
        }
    }
}

希望这能帮到你!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接