当前位置: 移动技术网 > IT编程>移动开发>Android > Android 复制文本内容到系统剪贴板的最简单实例(分享)

Android 复制文本内容到系统剪贴板的最简单实例(分享)

2019年07月24日  | 移动技术网IT编程  | 我要评论

志愿北京网站,999全讯网,雨燕子

这个例子很简单,直接上截图和代码。

布局文件activity_copy.xml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

  <textview
    android:id="@+id/tvmsg"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="记者问一路人:“大妈,您觉得雾霾影响大吗?”路人:“能不大吗?首先你要看清楚,我是你大爷。"
    android:textsize="20sp" />

  <button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margintop="20dp"
    android:onclick="onclickcopy"
    android:text="复制上面的文本内容" />

</linearlayout>

后台copyactivity.java代码如下:

package chengyujia.demo.aty;

import android.content.context;
import android.os.bundle;
import android.text.clipboardmanager;
import android.view.view;
import android.widget.textview;
import android.widget.toast;
import chengyujia.demo.r;

public class copyactivity extends baseactivity {

  private textview tvmsg;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_copy);
    tvmsg = (textview) findviewbyid(r.id.tvmsg);
  }

  public void onclickcopy(view v) {
    // 从api11开始android推荐使用android.content.clipboardmanager
    // 为了兼容低版本我们这里使用旧版的android.text.clipboardmanager,虽然提示deprecated,但不影响使用。
    clipboardmanager cm = (clipboardmanager) getsystemservice(context.clipboard_service);
    // 将文本内容放到系统剪贴板里。
    cm.settext(tvmsg.gettext());
    toast.maketext(this, "复制成功,可以发给朋友们了。", toast.length_long).show();
  }
}

核心代码就两句:

clipboardmanager cm = (clipboardmanager) getsystemservice(context.clipboard_service);

cm.settext(要复制的文本内容);

以上这篇android 复制文本内容到系统剪贴板的最简单实例(分享)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网