Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why softkeyboard won't display in Fragment with WebView

I am using the compatibility package and I have a Fragment who returns a WebView in onCreateView. The problem is if the fragment isn't added during onCreate of the Activity then when a textbox is clicked inside of the WebView the softkeyboard is not displayed. If the device is rotated after the the custom web fragment has been added, recreating the activity, then the softkeyboard is displayed when clicking on a text field.

Just to be clear Here are the two different scenarios

public void onCreate(Bundle state){
   if(state == null){
      WebFragment web = new WebFragment();
      getSupportFragmentManager.beginTransaction().add(android.R.id.content, web).commit();
   }
}



public void onClick(View v){
      WebFragment web = new WebFragment();
      getSupportFragmentManager.beginTransaction().add(android.R.id.content, web).commit();
}

In the first case when adding the fragment during the Activity onCreate method then the WebView contained in the fragment works as it should when text fields are pressed. However, in the second example nothing happens when clicking a text field in the webview unless you rotate the device after the webview had been displayed. Can someone offer up a solution, if I have to create a new activity for my fragment to work properly it sorta beats the purpose of the fragment in the first place.

like image 500
Nathan Schwermann Avatar asked Apr 18 '11 21:04

Nathan Schwermann


1 Answers

Add this to the onCreateView method of the Fragment

webview.setOnTouchListener(new View.OnTouchListener() {
    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;
    }
});  

Tested with android 2.3.3 and 3.2.0.

Based on issue #7189 and StackOverflow

like image 75
k7k0 Avatar answered Sep 29 '22 01:09

k7k0