1.在activity_main.xml添加一个Button
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="使用剪切板传递数据" />
2.新建activity_other.xml 添加一个TextView
<TextView
android:id="@+id/msg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
></TextView>
3.在MainActivity添加以下代码
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 从android系统调用剪切板的服务
ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
String name ="以德服人";
cm.setText(name);
Intent intent = new Intent(MainActivity.this,OtherActivity.class);
startActivity(intent);
}
});
}
}
4,新增一个OtherActivity.java
public class OtherActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
textView = (TextView) findViewById(R.id.msg);
ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
String msgString = cm.getText().toString();
textView.setText(msgString);
}
}
5.在清单文件添加<activity android:name=".OtherActivity"></activity>