WebView textarea doesn't pop up the keyboard
Asked Answered
L

12

41

When I display a WebView, I don't see the soft keyboard popping up. The hard keyboard also doesn't work!

What are the usual shortcomings.

The code which I use to access the WebView is:

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);
}
}
Longdistance answered 11/8, 2010 at 17:4 Comment(5)
do you mean that the keyboard doesn't pop up when you are on the web page, or when you click inside a textarea?Isothere
maybe he means an html input field within a website that's displayed in the webview?Reclusion
@Sephny: When I click on the textarea, the keyboard doesn't pop up nor the hard keyboard available on a Motorola Milestone works!Longdistance
mm that's strange indeed. I ran some tests and had no trouble opening the keyboard with the simplest webview. Can you add the code you use for your webview?Isothere
I had this problem myself too, and it's webpage specific. I wasn't able to tackle it. Maybe try setting the focus to the webview by code, or use the trackball to navigate too. If you find the solution please share with us.Up
L
37

The problem was that webview wasn't getting focus when it was loaded hence using

webView.requestFocus(View.FOCUS_DOWN);

solved the problem.

Longdistance answered 24/11, 2010 at 1:44 Comment(2)
this solution did not help for nexus 7 with jelly bean, anyone have other ideas?Nisi
I had this issue on devices < HONEYCOMB. This fix alone did not work. But adding OnTouchListener code as suggested by Jeff Peiffer (above) did the trick.Grabble
B
46

The full solution is a bit more than what Sana had. It is documented as a bug over at the Android site ( 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;
    }
});
Bailey answered 26/7, 2011 at 1:25 Comment(1)
It worked for me, without this line: webView.requestFocus(View.FOCUS_DOWN);.Blanche
L
37

The problem was that webview wasn't getting focus when it was loaded hence using

webView.requestFocus(View.FOCUS_DOWN);

solved the problem.

Longdistance answered 24/11, 2010 at 1:44 Comment(2)
this solution did not help for nexus 7 with jelly bean, anyone have other ideas?Nisi
I had this issue on devices < HONEYCOMB. This fix alone did not work. But adding OnTouchListener code as suggested by Jeff Peiffer (above) did the trick.Grabble
B
8

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.

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:

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);
    }
}
Benefice answered 16/11, 2012 at 14:39 Comment(3)
In Jelly Bean +, none of the other solutions worked. This should be the accepted answer!Dupuy
@RuslanK Thanks for solution, But i dont see where is MyWebView is used ? I am using webview like this - It gives me error if i replace MyWebview inplace of Webview mWebView = (WebView) findViewById(R.id.webview);Calcite
@Manisha: first you should replace 'WebView' with 'com.mypackage.MyWebview' in the xml-file with your layout.Benefice
B
6

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

Brelje answered 3/4, 2013 at 18:11 Comment(0)
R
5

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" />
Rom answered 24/10, 2013 at 9:11 Comment(2)
Sad that I tried your option after trying all the above answers!!Heteroplasty
For me the same, the only answer that worked. I set it during runtime --> setFocusable(true); setFocusableInTouchMode(true);Barbarous
T
4

For those of you looking for a solution when the WebView is in an AlertDialog, the answer here solved this problem for me: Show soft keyboard in AlertDialog with a WebView inside (Android)

Tomfoolery answered 9/12, 2012 at 20:57 Comment(0)
D
1

I had the same problem on Jelly Bean, but none of the above solutions worked for me. This solution worked for me on JellyBean

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

Sometimes the android.R.attr.webViewStyle is not applied by default. This ensures that the style is always applied.

Dniester answered 20/11, 2012 at 15:26 Comment(0)
N
0

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?

Nisbet answered 12/11, 2010 at 10:40 Comment(0)
Q
0

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. 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. Less change of the overlay.

Hope this helps you.

Quiff answered 13/10, 2011 at 14:51 Comment(0)
C
0

try this --> the firstname is the name of the field and make sure it dose not have autofocus attribute.

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            mWebView.loadUrl("javascript:document.getElementById(\"firstname\").focus();");
        }
    });
Calcite answered 24/11, 2015 at 4:7 Comment(0)
G
0

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
    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>
Governorship answered 25/9, 2017 at 10:14 Comment(0)
G
0

override onPageFinished in WebViewClient

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)
}
Gummous answered 26/1, 2022 at 10:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.