In the process of integrating a Javascript game into a webview I needed to have buttons injection keybard events in the webview.
The process is fairly simple and can be used on any type of view:
webView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT));
You can choose any keypress event, here I used the left keyboard arrow.
Here is the complete snippet code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import android.app.Activity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupView(); } private void setupView() { webView = (WebView) findViewById(R.id.webview); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); webView.loadUrl("file:///android_asset/index.html"); findViewById(R.id.left).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)); } }); findViewById(R.id.right).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { webView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT)); } }); } } |
and the layout where R.id.right and R.id.left are buttons:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent"></WebView> <Button android:id="@+id/left" android:text="left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_margin="10dp" android:layout_alignParentLeft="true"/> <Button android:id="@+id/right" android:text="right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_margin="10dp" /> </RelativeLayout> |
Which looks like this with the HTML / JS and CSS loaded:
Hope this will be usefull for you!
Leave a Reply