将一个程序的某些文件复制到剪切板上,可在任何程序中调用
实例:
布局:
acticity_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="使用剪切板传递数据" />
</RelativeLayout>
activity_other:
<?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" >
<TextView
android:id="@+id/msg"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
代码:
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) this.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
//从安卓系统调用剪切板服务
ClipboardManager clipboardManager=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
String name="xiaoming";
clipboardManager.setText(name);
Intent intent =new Intent(MainActivity.this,OtherActivity.class);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
OhterActivity:
public class OtherActivity extends Activity{
private TextView textView;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textView=(TextView) this.findViewById(R.id.msg);
ClipboardManager clipboardManager=(ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
String msgClip=clipboardManager.getPrimaryClip().toString();
textView.setText(msgClip);
}
}