android|android 剪贴板 ClipboardManager

【android|android 剪贴板 ClipboardManager】想做文件管理器中对文件的复制和粘贴功能。想到用ClipboardManager,其中可以放三种数据 text、intent、uri,为ClipData类型。我用的uri做了个小demo,话不多说上代码。
布局文件activity_main.xml



2.java文件

package com.example.clipboard; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.ClipData; import android.content.ClipboardManager; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener { private ClipboardManager clipboard = null; private final String PATH = "/mnt/sdcard/GPS.LOG"; private TextView textView; private Button copyButton; private Button pasteButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) this.findViewById(R.id.text); copyButton = (Button) this.findViewById(R.id.copy_button); pasteButton = (Button) this.findViewById(R.id.paste_button); copyButton.setOnClickListener(this); pasteButton.setOnClickListener(this); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") private void setclip() { //获得ClipboardManager对象 clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); //需要存入的内容 Uri uri = Uri.parse(PATH); //项内容转换为ClipData对象 ClipData clipData = https://www.it610.com/article/ClipData.newUri(getContentResolver(),"URI", uri); //存入剪贴板 clipboard.setPrimaryClip(clipData); } @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") private String getclip() { clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); ClipData.Item data= https://www.it610.com/article/clipboard.getPrimaryClip().getItemAt(0); Uri uri=data.getUri(); // String str = clipboard.getPrimaryClip().toString(); String path = uri.getEncodedPath(); return path; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.copy_button: setclip(); break; case R.id.paste_button: textView.setText("剪贴板内容:"+getclip()); break; default: break; } }}


运行结果: android|android 剪贴板 ClipboardManager
文章图片

    推荐阅读