main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击后复制" android:layout_centerHorizontal="true" android:layout_marginTop="100dip" /> <TextView android:id="@+id/textView" android:layout_width="150dip" android:layout_height="50dip" android:layout_centerInParent="true" android:hint="粘贴的内容" android:gravity="center" /> </RelativeLayout>
MainActivity如下:
package cn.com.testclipboardmanager; import android.os.Bundle; import android.text.ClipboardManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.app.Activity; import android.content.Context; /** * Demo描述: * 实现Android的复制,粘贴功能 */ public class MainActivity extends Activity { private Button mButton; private TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mTextView=(TextView) findViewById(R.id.textView); mTextView.setOnClickListener(new ClickListenerImpl()); mButton=(Button) findViewById(R.id.button); mButton.setOnClickListener(new ClickListenerImpl()); } private class ClickListenerImpl implements OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { //复制 case R.id.button: ClipboardManager copy = (ClipboardManager) MainActivity.this .getSystemService(Context.CLIPBOARD_SERVICE); copy.setText("Come On Baby"); break; //粘贴 case R.id.textView: ClipboardManager plaster = (ClipboardManager) MainActivity.this .getSystemService(Context.CLIPBOARD_SERVICE); String content=plaster.getText().toString().trim(); mTextView.setText(content); break; default: break; } } } }