在Android中,可以通过ClipboardManager服务来操作剪切板进行设置和读取操作!
运行界面UI效果:
复制-粘贴后的效果:
清除-粘贴的效果:
主要代码如下:
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ClipboardTestActivity extends Activity implements OnClickListener {
private EditText editText;
private Button copyButton;
private Button pasteButton;
private Button clearButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText = (EditText) findViewById(R.id.editText1);
copyButton = (Button) findViewById(R.id.button1);
pasteButton = (Button) findViewById(R.id.button2);
clearButton = (Button) findViewById(R.id.button3);
copyButton.setOnClickListener(this);
pasteButton.setOnClickListener(this);
clearButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
copy("Number:" + Math.random() * 100);
break;
case R.id.button2:
paste(editText);
break;
case R.id.button3:
clear();
break;
default:
break;
}
}
private void clear() {
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(null);
}
private void paste(EditText editText) {
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
CharSequence text = clipboardManager.getText();
if (TextUtils.isEmpty(text)) {
Toast.makeText(this, "The clipboard is empty!", Toast.LENGTH_SHORT).show();
return;
}
editText.setText(text);
}
private void copy(String text) {
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.setText(text);
}
}
说明:
- copy:随机产生一个数字,然后设置到剪贴板;
- paste:从剪贴板获得数据,并设置到EditText中进行显示;
- clear:清空剪贴板----其实和copy原理一样罢了;
布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dip"> <EditText android:id="@+id/editText1" android:layout_width="fill_parent" android:layout_height="wrap_content" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Copy" /> <Button android:id="@+id/button2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Paste" /> <Button android:id="@+id/button3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Clear" /> </LinearLayout>
多说一句:详细内容请参考开发者文档!:)