Как я могу получить изображение JPG в моем WebView в Android - PullRequest
1 голос
/ 29 мая 2010

У меня есть изображение JPG в моей папке ресурсов. Теперь я хочу, чтобы он отображался в моем WebView вместе с другим текстом в HTML, поступающим из поля базы данных. Как я могу получить / отобразить это изображение JPG?

Ответы [ 2 ]

2 голосов
/ 29 мая 2010

Вы можете попробовать:

android.resource: // package_name / ID_NUMBER

или

android.resource: // package_name / тип / имя

Подробнее см. Документацию по [openAssetFileDescriptor()] [1].

[1]: http://developer.android.com/reference/android/content/ContentResolver.html#openAssetFileDescriptor(android.net.Uri, java.lang.String)

0 голосов
/ 05 июля 2010

Вот полный код с изображением icon.png, отображаемым в WebView. Загляните в файл Demo.html, который находится в папке активов проекта. Запустите прилагаемый проект и дайте мне знать, если у вас есть другие вопросы.

WebViewDemo.java

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

/**
 * Demonstrates how to embed a WebView in your activity. Also demonstrates how
 * to have javascript in the WebView call into the activity, and how the activity 
 * can invoke javascript.
 * <p>
 * In this example, clicking on the android in the WebView will result in a call into
 * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code
 * will turn around and invoke javascript using the {@link WebView#loadUrl(String)}
 * method.
 * <p>
 * Obviously all of this could have been accomplished without calling into the activity
 * and then back into javascript, but this code is intended to show how to set up the 
 * code paths for this sort of communication.
 *
 */
public class WebViewDemo extends Activity {

    private static final String LOG_TAG = "WebViewDemo";

    private WebView mWebView;

    private Handler mHandler = new Handler();

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.webview);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(false);

        mWebView.setWebChromeClient(new MyWebChromeClient());

        mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");

        mWebView.loadUrl("file:///android_asset/demo.html");
    }

    final class DemoJavaScriptInterface {

        DemoJavaScriptInterface() {
        }

        /**
         * This is not called on the UI thread. Post a runnable to invoke
         * loadUrl on the UI thread.
         */
        public void clickOnAndroid() {
            mHandler.post(new Runnable() {
                public void run() {
                    mWebView.loadUrl("javascript:wave()");
                }
            });

        }
    }

    /**
     * Provides a hook for calling "alert" from javascript. Useful for
     * debugging your javascript.
     */
    final class MyWebChromeClient extends WebChromeClient {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(LOG_TAG, message);
            result.confirm();
            return true;
        }
    }
}

main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
            <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="@string/intro"
            android:padding="4dip"
            android:textSize="16sp"
            />

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent" 
        android:layout_height="0dip"
        android:layout_weight="1"
        />

</LinearLayout>

demo.html

<html>
        <script language="javascript">
            /* This function is invoked by the activity */
                function wave() {
                    alert("1");
                        document.getElementById("droid").src="android_waving.png";
                        alert("2");
                }
        </script>
        <body>
            <!-- Calls into the javascript interface for the activity -->
            <a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
                        margin:0px auto;
                        padding:10px;
                        text-align:center;
                        border:2px solid #202020;" >
                                <img id="droid" src="android_normal.png"/><br>
                                Click me!
                </div></a>
        </body>
</html>

strings.xml

<resources>
    <string name="intro">Demonstrates an embedded WebView and two-way communication between the HTML document and the hosting activity.</string>
    <string name="app_name">WebViewDemo</string>
</resources>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...