在Android Activity中从软件键盘中收听Webview Key Events

时间:2014-10-13 17:59:59

标签: android webview keyevent

是否可以从主机Android应用程序中的webview处理软件键盘事件?

例如,我的应用程序的“活动”是否可以在显示Google网站的网页浏览的搜索字段中收听键入的内容?

考虑到下面描述的方法,如果我覆盖它返回true,这将是可能的,但不幸的是我无法做到这一点。有什么想法吗?

public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)

Added in API level 1
Give the host application a chance to handle the key event synchronously. e.g. menu shortcut key     events need to be filtered this way. If return true, WebView will not handle the key event. If return false, WebView will always handle the key event, so none of the super in the view chain will see the key event. The default behavior returns false.

Parameters
view    The WebView that is initiating the callback.
event   The key event.
Returns
True if the host application wants to handle the key event itself, otherwise return false

2 个答案:

答案 0 :(得分:1)

我认为shouldOverrideKeyEvent方法只是告诉系统哪个“窗口”应该收到关键事件的通知;这样做 NOT 将WebView javascript事件传回活动。

如果您需要将信息从WebView传递到Activity,则可以使用JavascriptInterface。 请注意,这仅适用于您控制的网站;否则它将成为一个安全漏洞,为您的应用提供对敏感数据的访问权。

首先,创建一个类作为您的界面:

class MyJavaScriptInterface{
    //Methods to call via js in the WebView go here
}

然后在WebView上初始化界面:

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(new MyJavaScriptInterface(), "JSInterface");

现在,您说过要将文本字段中的类型内容传递回Activity。为此,为模糊上的文本字段注册事件监听器,当字段失去焦点时将触发该事件监听器。

<!-- HTML element to listen for blur -->
<input id="field" type="text" />

<script>
  //Communicate with Javascript Interface
  var jsFieldBlur = function(field){
      //Only call if the interface exists
      if(window.JSInterface){
          window.JSInterface.onFieldBlur(field.id, field.value);
      }
  };

  //Obtain reference to DOM element
  var field = document.getElementById("field");

  //Attach blur listener
  field.addEventListener("blur", function( event ) {
      jsFieldBlur(event.target);   
  }, true);
</script>

最后,我们需要将onFieldBlur方法添加到MyJavascriptInterface类中,以便可以通过javascript调用它。以这种方式定义的任何方法都必须以@JavascriptInterface开头才能对WebView可见。

class MyJavaScriptInterface{
    @JavascriptInterface
    public void onFieldBlur(String fieldId, String fieldValue){
        //Do something with value
        Toast.makeText(getContext(), fieldId+"="+fieldValue, Toast.LENGTH_LONG).show();
    }
}

答案 1 :(得分:0)

public class WebViewDemo extends Activity {

WebView myWebView;
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    myWebView = (WebView) findViewById(R.id.webview);
    myWebView.loadUrl("file:///android_asset/test.html");
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

   // myWebView.setWebViewClient(new WebViewClient());
    myWebView.setWebViewClient(new MyWebViewClient());
}

public class JavaScriptInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    JavaScriptInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
        startActivity(new Intent(WebViewDemo.this, WebViewDemo.class));
    }
}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals("www.google.com")) {
            // This is my web site, so do not override; let my WebView load the page
            Toast.makeText(getApplicationContext(), "www.google.com", Toast.LENGTH_SHORT).show();
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
    }
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    // Check if the key event was the BACK key and if there's history
    if ((keyCode ==  KeyEvent.KEYCODE_ENTER)) {

       // here you can got key event of enter key ( whether you used as for search of any other option

        return true;
    }
    // If it wasn't the BACK key or there's no web page history, bubble up to the default
    // system behavior (probably exit the activity)
    return super.onKeyDown(keyCode, event);
}

}

相关问题