2011-08-31 45 views
5

在一個有很多組件的Activity中,我有一個有WebView的RelativeLayout(它顯示一個簡單的文本,我不知道他的大小)。在Android中調整佈局的動態大小

這是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的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()...

我該如何解決這個問題?非常感謝你!

回答

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); 
     } 
    } 
} 

希望這有助於!