从android中的OnCreate之外的方法与webview进行交互

时间:2011-09-25 17:16:54

标签: android

我有一个问题一直在发生,我想知道如何解决它。我希望能够与视图进行交互,在这种情况下,特别是来自oncreate外部的webview,以便我的方法可以与oncreate中定义的webview进行交互。

以下是我尝试做的一个例子。在搜索语音阵列中我检查用户是否说“go”,如果他们确实想要按下go按钮或者只是执行go按钮会执行的代码。我希望我能够解释得这么好,如果你需要澄清请告诉我,提前谢谢!

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class web extends Activity {
    static final int check = 111;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web);
        final WebView webBrowser = (WebView) findViewById(R.id.webview);
        webBrowser.setWebViewClient(new cpViewClient());
        webBrowser.getSettings().setJavaScriptEnabled(true);
        webBrowser.getSettings().setLoadWithOverviewMode(true);
        webBrowser.getSettings().setUseWideViewPort(true);
        webBrowser.loadUrl("http://www.google.com");
        final InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

        Button bGo = (Button) findViewById(R.id.go);
        Button bBack = (Button) findViewById(R.id.back);
        Button bForward = (Button) findViewById(R.id.forward);
        Button bRefresh = (Button) findViewById(R.id.refresh);
        Button bClearHistory = (Button) findViewById(R.id.clearhistory);
        final EditText etUrl = (EditText) findViewById(R.id.url);

        bGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String enteredUrl = etUrl.getText().toString();
                enteredUrl = enteredUrl.toLowerCase();
                int len = enteredUrl.length();
                /*
                 * if (enteredUrl.substring(0, 3).equals("www")) enteredUrl =
                 * "http://" + enteredUrl; else if (enteredUrl.substring(0,
                 * 11).equals("http://www.")) //Do nothing its perfect
                 * Log.d("URL", "The Url is fine"); else enteredUrl =
                 * "http://www." + enteredUrl;
                 * 
                 * String dot1 = enteredUrl.substring(len-5, len-4); String dot2
                 * = enteredUrl.substring(len-4, len-3); if (!dot1.equals(".")
                 * || !dot2.equals(".")) enteredUrl = enteredUrl + ".com";
                 */
                if (enteredUrl.indexOf("http://") == -1
                        & enteredUrl.indexOf("www.") == -1) {
                    enteredUrl = "http://www." + enteredUrl;
                } else if (enteredUrl.indexOf("http://") == -1) {
                    enteredUrl = "http://" + enteredUrl;
                }

                if (enteredUrl.indexOf(".com") == -1
                        & enteredUrl.indexOf(".org") == -1
                        & enteredUrl.indexOf(".net") == -1
                        & enteredUrl.indexOf(".mil") == -1
                        & enteredUrl.indexOf(".gov") == -1
                        & enteredUrl.indexOf(".edu") == -1
                        & enteredUrl.indexOf(".info") == -1) {
                    enteredUrl = enteredUrl + ".com";
                }

                webBrowser.loadUrl(enteredUrl);
                etUrl.setText(enteredUrl);
                imm.hideSoftInputFromWindow(etUrl.getWindowToken(), 0);
            }

        });
        bBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (webBrowser.canGoBack())
                    webBrowser.goBack();
            }

        });
        bForward.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (webBrowser.canGoForward())
                    webBrowser.goForward();
            }

        });
        bRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webBrowser.reload();
            }

        });
        bClearHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webBrowser.clearHistory();
            }

        });
        Button VR = (Button) findViewById(R.id.webvoice);
        VR.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                getvoice();
            }

        });



    }
    public void getvoice() {
        Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        startActivityForResult(i, check);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == check && resultCode == RESULT_OK) {
            result = data
                    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            final TextView tvvoicearray = (TextView) findViewById(R.id.tvvoicearray);
            tvvoicearray.setText(result.get(0));
            searchvoicearray();
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    public void searchvoicearray() {
        // Log.d("DEBUGGINGG",result.get(0));
        // System.out.println(result);
        int size = result.size();
        int i = 0;
        while (i < size) {
            String s = result.get(i);
            // next line removes all spaces in the string
            // s= s.replaceAll(" ", "");
            if (s.indexOf("go") != -1 ) {
                i = size;
                //i want the button go to be pressed or its action to be completed.

                if (webBrowser.canGoBack())
                webBrowser.goBack();
            } 

            else if (s.indexOf("back") != -1) {
                i = size;
                if (webBrowser.canGoBack())
                    webBrowser.goBack();
            } 

            else {
                System.out.println(result.get(i) + " is not internet");
                Log.d("DEBUGGINGG", result.get(i) + " is not internet");
                // }
                i++;
            }
        }

    }

    ArrayList<String> result = new ArrayList<String>();

}

2 个答案:

答案 0 :(得分:1)

然后,在onCreate之外声明webview:

static final int check = 111;
private WebView webBrowser;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.web);
    webBrowser = (WebView) findViewById(R.id.webview);

答案 1 :(得分:1)

您需要使WebView成为 web 类的成员而不是onCreate()方法的本地变量:要执行此操作,只需将其声明移到方法之外:

public class web extends Activity {

    //Declare your member objects/variables here
    static final int check = 111;
    WebView webBrowser;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.web);
        webBrowser = (WebView) findViewById(R.id.webview);
        ...
        }
...        
}