Friday, February 5, 2016

Clipboard Notes

I just added clipboard code to a project I'm going to release soon.  Strangely, it went in easy and worked without problems the first time.  I don't know if that means I'm better at Android or the Clipboard code didn't need me to unwind and figure out dependency within dependency and special rules for sequencing calls for whatever part of the Activity life-cycle an update was happening inside of, with a fragment, for a certain phone, on a Tuesday.

Whatever...Android.

Some quick notes on how to make the clipboard work for text, so next time I don't have to go "groveling docs", as a former co-worker of mine used to say:

Here's the basic way to get an item to the clipboard using "newPlainText" as a shorthand method:

ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
clip = ClipData.newPlainText("simple text""string for the clipboard goes here" );
clipboard.setPrimaryClip(clip); // Set the ClipData to the clipboard. One ClipData instance only.

Here's how to populate a ClipData with multiple ClipData.Item instances, so multiple lines of (plain text) data can be added to the clipboard.  The ClipData constructors need a ClipData.Item, so I put the call to instantiate within the loop after checking for null:

ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = null;

while( it.hasNext()) {
   ClipData.Item item = new ClipData.Item( it.next().toString());

   // Initialize the clip the first time through.  Subsequent items are added to the clip via addItem.
   if( clip == null ) {
      ClipDescription desc = new ClipDescription( "simple text", new String[] { ClipDescription.MIMETYPE_TEXT_HTML } );
      clip = new ClipData(desc, item );
   }
   else {
      clip.addItem( item );
   }
}

// The populated clip with added items is added to the clipboard.
clipboard.setPrimaryClip(clip);

It's nice to have something work without having it turn into a jigsaw puzzle.

No comments:

Post a Comment