2011年3月29日 星期二

[Android] Copy & Paste (for Android 2.x only)

I design two EditText control, and menu for copy and paste.
User can input text at the first EditText control, then click menu 'Copy'.
As long as user click the menu 'Paste', the same text would paste into the second EditText.


We should give id to EditText for access the control in 'res/layout/main.xml'.

<EditText
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/editText1"android:hint="input text here"
/>
<EditText
android:layout_height="wrap_content"
android:text=""
android:layout_width="fill_parent"
android:id="@+id/editText2"
android:hint="text will be paste in here."
/>


When user select menu item, let do something...

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
 //ClipboardManager object can easily manage copy and paste.
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

switch(item.getItemId())
{
case (MENU_COPY):
    clipboard.setText(mEditText1.getText());
case (MENU_PASTE):
    mEditText2.setText(clipboard.getText());
}

return super.onMenuItemSelected(featureId, item);
}

沒有留言:

張貼留言