简体   繁体   English

WebView textarea 不弹出键盘

[英]WebView textarea doesn't pop up the keyboard

When I display a WebView , I don't see the soft keyboard popping up.当我显示WebView时,我看不到软键盘弹出。 The hard keyboard also doesn't work!硬键盘也不行!

What are the usual shortcomings.常见的缺点是什么。

The code which I use to access the WebView is:我用来访问WebView的代码是:

package com.example.blahblah;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class createAccount extends Activity {

private static final String LOG_TAG = "Create Account";
private WebView mWebView;
private static final String URL = blah_app.urlSelected+"createAccount.html";    
private Handler mHandler = new Handler();

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    Toast.makeText(createAccount.this, "URL = " +URL, Toast.LENGTH_SHORT).show();
    getWindow().requestFeature(Window.FEATURE_PROGRESS);
    setContentView(R.layout.webview);
    getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

    mWebView = (WebView) findViewById(R.id.webview);

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


    final Activity activity = this;
    mWebView.setWebChromeClient(new WebChromeClient() {
    public void onProgressChanged(WebView view, int progress) {

        activity.setProgress(progress * 1000);
      }
    });

    mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
    mWebView.clearCache(true);
    setProgressBarVisibility(true);
    mWebView.setWebViewClient(new WebViewClient() {
          public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
          }

           @Override  
           public void onPageFinished(WebView view, String url)  
           {  
               mWebView.loadUrl("javascript:(function () { " +
                       "setVariables("+blah_app.numberSelected+",'"+blah_app.urlSelected+"');" +
                       "})()");
           }
        });

    mWebView.loadUrl(URL);
}

final class DemoJavaScriptInterface {

    public void setData(String fname, String lname, String gacct, String phone) {

        SharedPreferences prefCreateAccount = PreferenceManager.getDefaultSharedPreferences(createAccount.this);
        SharedPreferences.Editor editor = prefCreateAccount.edit();
        editor.putString("FirstName", fname);
        editor.putString("LastName", lname);
        editor.putString("GmailAcct", gacct);
        editor.putString("Phone", phone);
        editor.commit();    

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

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        startActivity(new Intent(getApplication(), blah_app.class));
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
}

The full solution is a bit more than what Sana had. 完整的解决方案比Sana更多。 It is documented as a bug over at the Android site ( http://code.google.com/p/android/issues/detail?id=7189 ): 它被记录为Android网站上的错误( http://code.google.com/p/android/issues/detail?id=7189 ):

webView.requestFocus(View.FOCUS_DOWN);
webView.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus())
                {
                    v.requestFocus();
                }
                break;
        }
        return false;
    }
});

The problem was that webview wasn't getting focus when it was loaded hence using 问题是webview在加载时没有得到焦点因此使用

webView.requestFocus(View.FOCUS_DOWN);

solved the problem. 解决了这个问题。

I'm surprised that even on Android 4.1 (tested on SGS3) the problem is still present, and overriding onTouch() don't solve it for me. 我很惊讶,即使在Android 4.1(在SGS3上测试)问题仍然存在,并且覆盖onTouch()并不能解决它。

Test code: 测试代码:

String HTML = "<html><head>TEST</head><body><form>";
HTML += "<INPUT TYPE=TEXT SIZE=40 NAME=user value=\"your name\">";
HTML += "</form></body></html>";

WebView wv = new WebView(getContext());
wv.loadData(HTML, "text/html", null);

final AlertDialog.Builder adb = new AlertDialog.Builder(getContext());
adb.setTitle("TEST").setView(wv).show();

My complex solution is replace WebView with MyWebView: 我的复杂解决方案是用MyWebView替换WebView:

private static class MyWebView extends WebView
{
    public MyWebView(Context context)
    {
        super(context);
    }

    // Note this!
    @Override
    public boolean onCheckIsTextEditor()
    {
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        switch (ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!hasFocus())
                    requestFocus();
            break;
        }

        return super.onTouchEvent(ev);
    }
}

one line answer and it is working nicely 一线答案,它运作良好

// define webview for browser
wb = (WebView) findViewById(R.id.webView1);
wb.requestFocusFromTouch();

where wb is my object of webView 其中wb是我的webView对象

Had the same issue and non of the above solutions worked. 有相同的问题,而不是上述解决方案的工作。 This woked for me 这对我说

    <CustomWebView
    android:id="@+id/webView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:focusable="true"
    android:focusableInTouchMode="true" />

对于那些在WebView处于AlertDialog时寻找解决方案的人AlertDialog ,这里的答案为我解决了这个问题: 在AlertDialog中显示带有WebView的软键盘(Android)

I had the same problem on Jelly Bean, but none of the above solutions worked for me. 我在Jelly Bean上遇到了同样的问题,但上述解决方案都没有对我有用。 This solution worked for me on JellyBean 这个解决方案适用于JellyBean

WebView webView = new WebView(getActivity(), null, android.R.attr.webViewStyle);

Sometimes the android.R.attr.webViewStyle is not applied by default. 有时默认情况下不应用android.R.attr.webViewStyle。 This ensures that the style is always applied. 这可确保始终应用样式。

try this --> the firstname is the name of the field and make sure it dose not have autofocus attribute. 试试这个 - > firstname是字段的名称,并确保它没有autofocus属性。

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            mWebView.loadUrl("javascript:document.getElementById(\"firstname\").focus();");
        }
    });

I had a similar problem.... and later i found that the text box on the web page that my web view shown was disabled. 我遇到了类似的问题....后来我发现我的网页视图显示的网页上的文本框已被禁用。

Check this if the page has same problem in browser? 如果页面在浏览器中有相同问题,请检查此项?

For making it easy, and as the other solutions have issues working on all devices or in all condition, I'm always using a small hack to overcome this issue without touching the code, just add any hidden editText to the layout contains the webView that will grant the focus to the whole view automatically and you will not have to worry about the webView text fields anymore: 为了使它变得简单,并且由于其他解决方案在所有设备或所有条件下都有问题,我总是使用小黑客来克服这个问题而不触及代码,只需将任何隐藏的editText添加到包含webView的布局中将自动将焦点放在整个视图上,您​​将不再需要担心webView文本字段:

<EditText
    android:id="@+id/kb_holder"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:inputType="text"
    android:maxLines="1"
    android:visibility="gone" /> 

So, the whole layout would be like: 所以,整个布局就像:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/kb_holder"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:inputType="text"
        android:maxLines="1"
        android:visibility="gone" />

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

override onPageFinished in WebViewClient在 WebViewClient 中覆盖 onPageFinished

override fun onPageFinished(view: WebView?, url: String?) {
 
    // Show soft input automatically for specific search web page.
    if ("the_url_page".equals(url)) {
        view?.requestFocus()
        val imm: InputMethodManager? = view?.context?.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
            imm?.showSoftInput(view, 0)
    }
    super.onPageFinished(view, url)
}

I was having the exact same problem none of the above solutions worked for me. 我遇到了完全相同的问题,上述解决方案都没有对我有用。 After ages of trying i finally found the problem. 经过多年的努力,我终于找到了问题。

Some of the various web pages I was rendering with WebView didn't fit properly into the Web view and as a result a div (or some other html component ) were being invisibly laid over the input fields. 我使用WebView渲染的各种网页中的一些不适合Web视图,因此div(或其他一些html组件)无形地放在输入字段上。 Although the input fields appeared selected when touched, they would not allow text input (even if i did manage to get the soft keyboard up using the track ball). 尽管输入字段在触摸时显示为选中状态,但它们不允许输入文本(即使我确实设法使用跟踪球获得软键盘)。

So the solution. 所以解决方案。

WebView.getSettings().setUseWideViewPort(true);

This won't completely stop the issue, but makes the view more like a PC browser which sites are designed for. 这不会完全阻止这个问题,但会使视图更像是一个PC浏览器,它们是为哪些网站设计的。 Less change of the overlay. 覆盖变化较小。

Hope this helps you. 希望这对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM