Sunday, October 14, 2012

Copy Text in a WebView in Android 2.3 and Below

Copy functionality in a WebView is available by default in Android 3.0 and above.  To enable copy in version below 3.0, there is a little code that has to be added.  The first thing I did was add a Copy button to my Actionbar at the bottom of the view.

ImageButton copyButton = (ImageButton)findViewById(R.id.copyButton);
if(Build.VERSION.SDK_INT < 11) 
{
    copyButton.setOnClickListener(new OnClickListener() 
    {
              
          public void onClick(View v) 
          {
              emulateShiftHeld(webView);

          }
      });
}
else
{
    copyButton.setVisibility(View.GONE);
}

The code checks to see if the version of Android is less than 11 which is Honeycomb. If it is, then the emulateShiftHeld() method is called. If the version is 11 or above, the Copy button is not needed (copy is available by default), so the Copy button is hidden. Here is the code for emulateShiftHeld()

private void emulateShiftHeld(WebView view)
{
    try
    {
        KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
        shiftPressEvent.dispatch(view);
        if(Build.VERSION.SDK_INT == 10) 
        {
            Toast.makeText(this, "Select Text then tap the text", Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(this, "Select Text", Toast.LENGTH_LONG).show();
        }

    }
    catch (Exception e)
    {
        Log.e("dd", "Exception in emulateShiftHeld()", e);
    }

}

The behavior of Gingerbread is different from versions before Gingerbread. In Gingerbread (version 10), the user has to select the text to copy and then tap the screen to have it added to the clipboard. In earlier versions, when the user conpletes the selection, the text is automatically added to the clipboard. Because of the different ways to copy, the version is checked and different instructions are displayed in a Toast.

You can get the code from our repository in GitHub. Connexions for Android is available in the Google Play Store or from the Connexions website.