Sunday, June 24, 2012

Apertium Android Clipboard handling added

Although the translated text is rendered on android.widget.EditText from which user can select and copy. But having a feature to automatic copying of text to clipboard helps more. Also, there is a option to fill input text field from text on clipboard.

Implementation Technique 

Android two entirely different version of clipboardmanger for API Level less than 11 and 11 or more. The build target has been set to Api 7 to 15, preferably 10
Preview of Manifest file

The API level of android has been fetch on run-time and executing the code accordingly
Preview of ClipBoardManager.java
 @SuppressWarnings("deprecation")
 public void putText(String text){
   int sdk = android.os.Build.VERSION.SDK_INT;
   if(sdk < 11) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText(text);
   } else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); 
    android.content.ClipData clip = ClipData.newPlainText("simple text",text);
    clipboard.setPrimaryClip(clip);
   }
 }
 
 @SuppressWarnings("deprecation")
 public String getText(){
  String text = null;
   int sdk = android.os.Build.VERSION.SDK_INT;
   if(sdk < 11) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
    text =  clipboard.getText().toString();
   } else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE); 
    text =  clipboard.getText().toString();
   }
  return text;
 }

Thumbnail

Figure 1
Showing setting panel with ClipBoard options

SEE IT ON GITHUB

2 comments:

  1. I think this will fail on older devices during class loading as you directly refer classes that doesent exists on older devices.

    You'll have to use reflection or wrapper class, see http://developer.android.com/resources/articles/backward-compatibility.html

    (currently offline, so see
    http://webcache.googleusercontent.com/search?q=cache:_M3funiORScJ:developer.android.com/resources/articles/backward-compatibility.html+&cd=1&hl=eo&ct=clnk&gl=dk&lr=lang_da%7Clang_eo )

    Jacob

    ReplyDelete
  2. First I am finding the API version of Android on device. Then I am calling classes accordingly.
    See line #19,20 above (Preview of ClipBoardManager.java)

    For API < 11
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager)activity.getSystemService(Context.CLIPBOARD_SERVICE);
    text = clipboard.getText().toString();

    For API >= 11
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
    text = clipboard.getText().toString();

    ReplyDelete