3

我在尝试在我的应用程序中将 WebView 背景设置为透明时遇到问题。我发现了很多类似的问题和解决方法,如何将 WebView 背景设置为透明。API > 11 最流行的解决方案是:

// Color.TRANSPARENT or 0x00000000 or simple 0 as a value
webview.setBackgroundColor(Color.TRANSPARENT); 
if (Build.VERSION.SDK_INT >= 11){
   setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}

但是,当我将此行添加到 setLayerType(WebView.LAYER_TYPE_SOFTWARE, null) 时,webview 中的 HTML 内容就会消失。Webview 本身具有正确的比例(内容的高度)、滚动,甚至在点击或点击它时做出反应(我有图像缩放系统在点击)。但是内容没有显示。

如果我删除 setLayerType() 方法内容显示正常,但它在滚动时闪烁。

我使用 Android 4.2.2 JB (API 17) 并且整个应用程序的 hardwareAcceleration 设置为 true。我的 HTML 内容正文 CSS 设置为

background:transparent;

此外,我的 WebView 与其他 2 个 TextView 和 RelativeLayout 一起放置在相对视图内,并将相对布局本身放置在 ScrollView 内。

我还没有为我的案例找到任何解决方案 - 我发现的所有建议都是将 setLayerType() 设置为软件。

4

1 回答 1

0

我有同样的问题,但问题是我的 webview 在滚动视图内:

<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="@string/alert.resume"
        android:textColor="#ff000000"
        android:textSize="14sp" />

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>

然后,我删除了滚动视图,这个技巧奏效了!

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:text="@string/alert.resume"
    android:textColor="#ff000000"
    android:textSize="14sp" />

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
 </LinearLayout>

像往常一样把戏:

WebView text = (WebView) view.findViewById(R.id.webview);
    text.setDrawingCacheEnabled(false);
    WebSettings settings = text.getSettings();
    settings.setDefaultTextEncodingName("utf-8");
    text.setBackgroundColor(Color.TRANSPARENT);
        if (Build.VERSION.SDK_INT >= 11) // Android v3.0+
            try {
            text.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
            } catch (Exception e) {
            }
于 2013-06-17T09:56:32.083 回答