Android: Implement copy-paste function

Table of contents

1. Introduction

(1) Introduction to ClipboardManager

1. Common methods of ClipboardManager:

2. Get the ClipboardManager instance

(2) Introduction to ClipData

1. Create a ClipData object:

2. Get ClipData information:

3. ClipData.Item object:

2. Examples

Copy-paste helper class ClipboardHelper: 

 MainActivity:

 activity_main:

 operation result:


1. Introduction

(one)ClipboardManager介绍

    ClipboardManagerIt is a system service provided by Android for managing clipboard contents. It allows you to copy and paste data such as text, links, images, etc. between applications.

1、ClipboardManagerCommonly used methods:

  • setPrimaryClip(ClipData clip): Set the specified ClipDataobject as the main clipboard content. This can be used to copy text, links, images, etc. to the clipboard.
ClipData clipData = ClipData.newPlainText("label", "要复制的文本");
clipboardManager.setPrimaryClip(clipData);
  • getPrimaryClip(): Get the contents of the main clipboard. Returns an ClipDataobject containing the data from the main clipboard.
ClipData clipData = clipboardManager.getPrimaryClip();
if (clipData != null && clipData.getItemCount() > 0) {
    // 处理剪贴板内容
}
  • hasPrimaryClip(): Check if the main clipboard has content. Returns if the clipboard contains data, trueotherwise false.
if (clipboardManager.hasPrimaryClip()) {
    ClipData clipData = clipboardManager.getPrimaryClip();
    if (clipData != null && clipData.getItemCount() > 0) {
        CharSequence text = clipData.getItemAt(0).getText();
        // 使用获取到的文本进行操作
    }
}
  • addPrimaryClipChangedListener(OnPrimaryClipChangedListener listener): Register a clipboard change listener to receive notifications when the clipboard content changes.
clipboardManager.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
    @Override
    public void onPrimaryClipChanged() {
        // 剪贴板内容发生变化时执行相关操作
    }
});

2. Get ClipboardManager实例

ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

(二)、ClipData介绍

         ClipDataIs a class used in Android to store data in the clipboard. It is an immutable data container that can contain one or more ClipData.Itemobjects, each object representing an item of clipboard content.

1. Create ClipDataobjects:

You can use ClipDatathe static methods of the class newPlainText()or newUri()to create a new ClipDataobject.

  • newPlainText(CharSequence label, CharSequence text): Create a plain text ClipDataobject. You need to provide a label (label) and the text content (text) to be copied to the clipboard.
CharSequence label = "Label";
CharSequence text = "要复制的文本";
ClipData clipData = ClipData.newPlainText(label, text);
  • newUri(ContentResolver resolver, CharSequence label, Uri uri)ClipData: Create an object containing a URI . You need to provide a label, a ContentResolver, and a URI to copy to the clipboard.
CharSequence label = "Label";
Uri uri = Uri.parse("https://example.com");
ClipData clipData = ClipData.newUri(getContentResolver(), label, uri);

2. ClipDataInformation obtained:

         ClipDataThe object contains the data from the clipboard. ClipDataYou can access and manipulate content using the following methods :

  • getItemCount(): Get the number of items ( ) ClipDatacontained in .ClipData.Item
int itemCount = clipData.getItemCount();
  • getItemAt(int index): Get the value at the specified index ClipData.Item.
ClipData.Item item = clipData.getItemAt(index);

3、ClipData.ItemObject:

    ClipData.ItemRepresents an item in the clipboard, which can be text, a link, or other data. You can access and manipulate each object through ClipDatamethods Item

  • getText(): Get ClipData.Itemthe text content.
CharSequence text = item.getText();
  • getUri(): ClipData.ItemURI being retrieved.
Uri uri = item.getUri();

2. Examples

Copy-paste helper class ClipboardHelper: 

package com.example.stardemo;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;

public class ClipboardHelper {

    private Context context;
    private ClipboardManager clipboardManager;

    public ClipboardHelper(Context context) {
        this.context = context;
        clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    }

    /**
     * 将文本复制到剪贴板
     *
     * @param text 要复制的文本
     */
    public void copyText(String text) {
        ClipData clipData = ClipData.newPlainText("text", text);
        clipboardManager.setPrimaryClip(clipData);
    }

    /**
     * 从剪贴板获取文本
     *
     * @return 剪贴板中的文本
     */
    public String getCopiedText() {
        if (clipboardManager.hasPrimaryClip()) {
            ClipData clipData = clipboardManager.getPrimaryClip();
            if (clipData != null && clipData.getItemCount() > 0) {
                CharSequence text = clipData.getItemAt(0).getText();
                return text.toString();
            }
        }
        return null;
    }

}

 MainActivity:

package com.example.stardemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
TextView copeText,pasteText;
ClipboardHelper mClipboardHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        copeText = findViewById(R.id.copyText);
        pasteText = findViewById(R.id.pasteText);
        mClipboardHelper = new ClipboardHelper(this);
        copeText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mClipboardHelper.copyText(copeText.getText().toString());
                Toast.makeText(MainActivity.this, "复制成功", Toast.LENGTH_SHORT).show();
            }
        });
        pasteText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pasteText.setText(mClipboardHelper.getCopiedText());
                Toast.makeText(MainActivity.this, "粘贴成功", Toast.LENGTH_SHORT).show();
            }
        });

    }
}

            It contains two TextView: copyTextand pasteText. On click copyText, it will use ClipboardHelperthe class to copy the text to the clipboard and display a Toast message indicating that the copy was successful. On click pasteTextit will get the copied text from the clipboard and set it to pasteTextthe text of . 

 activity_main:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/copyText"
        android:layout_width="115dp"
        android:layout_height="100dp"
        android:gravity="center"
        android:text="Hello World!"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:textColor="@color/black"
        app:layout_constraintVertical_bias="0.234" />

    <TextView
        android:id="@+id/pasteText"
        android:background="@color/teal_200"
        android:textColor="@color/black"
        android:layout_width="115dp"
        android:layout_height="100dp"
        android:gravity="center"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.551" />

</androidx.constraintlayout.widget.ConstraintLayout>

 operation result:

Guess you like

Origin blog.csdn.net/A125679880/article/details/132113460