openplanning

Hướng dẫn và ví dụ Android Clipboard

  1. Android Clipboard
  2. Ví dụ: Clipboard (Plain Text)
  3. Ví dụ: Clipboard (Intent)
  4. Ví dụ: Clipboard (URI)

1. Android Clipboard

Trong Android, Clipboard là một nền tảng (framework) rất hữu ích cho việc sao chép (copy) và dán (paste) các kiểu khác nhau của dữ liệu, chẳng hạn: văn bản, hình ảnh (image), các dòng dữ liệu nhị phân (binary stream data), và các kiểu dữ liệu phức tạp khác.
Một cách cụ thể, nếu dữ liệu là kiểu văn bản đơn giản, khi sao chép nó sẽ được lưu trữ trực tiếp trong Clipboard.
Các dữ liệu phức tạp khi sao chép chúng sẽ được lưu trữ như một tham chiếu (reference). Và ứng dụng dán (pasting application) có thể phải sử dụng ContentProvider để phân tích nội dung.
Để sử dụng Android Clipboard Framework, ứng dụng của bạn cần đặt các dữ liệu vào đối tượng ClipData, sau đó đặt đối tượng này nên trên hệ thống Clipboard. Tất cả các ứng dụng nào thực hiện theo các quy tắc ở trên có thể sao chép và dán dữ liệu tới nhau.
Một đối tượng ClipData được tạo ra bởi một trong các phương thức tĩnh dưới đây:
* Copy & Paste *
private void doCopy()  {
    this.clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

    String txtCopy = "Hello World";
    
    // ClipData (Plain Text)
    ClipData clipData = ClipData.newPlainText("Some label", txtCopy);
    
    // Copy ClipData to Clipboard.
    this.clipboardManager.setPrimaryClip(clipData);
}

private void doPaste()  {
    ClipData primaryClipData = this.clipboardManager.getPrimaryClip();

    ClipData.Item item = primaryClipData.getItemAt(0);

    // Text in the Clipboard.
    String txtPaste = item.getText().toString();
}

2. Ví dụ: Clipboard (Plain Text)

Sao chép và dán các "văn bản thuần thúy" (Plain Text) là việc thông dụng và đơn giản nhất trong ứng dụng Android. Dưới đây là một ví dụ như vậy:
Giao diện của ứng dụng:
activity_main.xml
<?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/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="18dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Enter text to copy"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText_copy"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="text"
        android:text="Hello Everybody!"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_copy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Copy to Clipboard"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_copy" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Show Clipboard data"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_copy" />

    <EditText
        android:id="@+id/editText_paste"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/button_paste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Paste from Clipboard"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_paste" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.clipboardplaintextexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText editTextCopy;
    private EditText editTextPaste;

    private Button buttonCopy;
    private Button buttonPaste;

    private ClipboardManager clipboardManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        this.clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

        this.editTextCopy = (EditText) findViewById(R.id.editText_copy);
        this.editTextPaste = (EditText) findViewById(R.id.editText_paste);

        this.buttonCopy = (Button) findViewById(R.id.button_copy);
        this.buttonPaste = (Button) findViewById(R.id.button_paste);

        this.buttonCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCopy();
            }
        });
        this.buttonPaste.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPaste();
            }
        });
    }

    // User click on "Copy" button.
    private void doCopy()  {
        String txtCopy = this.editTextCopy.getText().toString();
        ClipData clipData = ClipData.newPlainText("text", txtCopy);

        // Copy ClipData to Clipboard.
        this.clipboardManager.setPrimaryClip(clipData);

        Toast.makeText(getApplicationContext(),"Data Copied to Clipboard", Toast.LENGTH_SHORT).show();
    }

    // User click on "Poste" button.
    private void doPaste()  {
        // Get ClipData from Clipboard.
        ClipData primaryClipData = this.clipboardManager.getPrimaryClip();
        ClipData.Item item = primaryClipData.getItemAt(0);

        String txtPaste = item.getText().toString();

        this.editTextPaste.setText(txtPaste);

        Toast.makeText(getApplicationContext(),"Data Pasted from Clipboard",Toast.LENGTH_SHORT).show();
    }

}

3. Ví dụ: Clipboard (Intent)

Các Intent cũng có thể được sao chép vào Clipbooard. Trong ví dụ này tôi sẽ tạo ra một Intent đơn giản để mở một URL trên trình duyệt. Chúng ta có thể sao chép Intent này vào Clipboard.
Giao diện của ví dụ:
activity_main.xml
<?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/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Intention to open a URL in the browser:"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText_url"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:ems="10"
        android:inputType="text"
        android:text="https://google.com"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <Button
        android:id="@+id/button_copy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Copy Intent to Clipboard"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_url" />

    <EditText
        android:id="@+id/editText_paste"
        android:layout_width="0dp"
        android:layout_height="120dp"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:background="#B2B5A4"
        android:ems="10"
        android:inputType="textMultiLine|text"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_copy" />

    <Button
        android:id="@+id/button_paste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Paste Intent from Clipboard and start It!"
        android:textAllCaps="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText_paste" />

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.clipboarditentexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private ClipboardManager clipboardManager;
    private Button buttonCopy;
    private Button buttonPaste;

    private EditText editTextUrl;
    private EditText editTextPaste;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // ClipboardManager:
        this.clipboardManager = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);

        this.editTextPaste = (EditText) this.findViewById(R.id.editText_paste);
        this.editTextUrl = (EditText) this.findViewById(R.id.editText_url);

        this.buttonCopy = (Button) this.findViewById(R.id.button_copy);
        this.buttonPaste = (Button) this.findViewById(R.id.button_paste);


        this.buttonCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCopy();
            }
        });

        this.buttonPaste.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPaste();
            }
        });
    }

    // Some Intent need to Copy to Clipboard.
    private Intent getOpenUrlIntent(String url)  {

        // Intent to open a URL.
        Intent openUrlIntent = new Intent(Intent.ACTION_VIEW);
        openUrlIntent.setData(Uri.parse(url));

        openUrlIntent.putExtra("copyTimeInMillis", new Date().getTime());
        openUrlIntent.putExtra("description", "Intent to open a URL");

        return openUrlIntent;
    }

    private void doCopy()  {
        String url = this.editTextUrl.getText().toString();
        Intent openUrlIntent = this.getOpenUrlIntent(url);

        ClipData clipData = ClipData.newIntent("Open URL Intent", openUrlIntent);

        // Copy ClipData to Clipboard.
        this.clipboardManager.setPrimaryClip(clipData);

        Toast.makeText(getApplicationContext(),"Data Copied to Clipboard", Toast.LENGTH_SHORT).show();
    }

    private void doPaste()  {
        // Get ClipData from Clipboard.
        ClipData primaryClipData = this.clipboardManager.getPrimaryClip();
        ClipData.Item item = primaryClipData.getItemAt(0);

        // Get Intent from Clipboard.
        Intent intentPaste = item.getIntent();

        this.editTextPaste.setText("");

        if(intentPaste == null)  {
            this.editTextPaste.setText("No Intent data in Clipboard!");
            return;
        }

        this.editTextPaste.append("description: " + intentPaste.getStringExtra( "description" ));
        this.editTextPaste.append("\n");
        this.editTextPaste.append("copyTimeInMillis: " + intentPaste.getLongExtra("copyTimeInMillis" ,0L));

        this.editTextPaste.append("\n");
        this.editTextPaste.append("Action: " + intentPaste.getAction());
        Uri uri = intentPaste.getData();

        this.editTextPaste.append("Uri: " + uri);

        // Start Activity (If you want).
        startActivity(intentPaste);

        Toast.makeText(getApplicationContext(),"Data Pasted from Clipboard",Toast.LENGTH_SHORT).show();
    }
}

4. Ví dụ: Clipboard (URI)

Để sao chép một dữ liệu ảnh, bạn cần chuyển đổi nó thành một Uri, và sao chép Uri này vào Clipboard. Trong ví dụ này tôi sẽ sao chép một ảnh trong thư mục "drawable" vào Clipboard.
Copy một vài file ảnh vào thư mục "drawable":
icon_cry.png
icon_feel_good.png
Trên Android Studio, chúng ta sẽ tạo một Activity mới tên là ImageActivity để hiển thị hình ảnh đã được sao chép vào trong Clipboard.
  • File > New > Activity > Empty Activity
Android Studio tạo ra 2 tập tin: ImageActivity.javaactivity_image.xml, đồng thời ImageActivity sẽ được đăng ký với AndroidManifest.xml:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.o7planning.clipboarduriexample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- ImageActivity -->
        <activity android:name=".ImageActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Giao diện của ImageActivity:
activity_image.xml
<?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/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Show  Image In Clipboard"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:srcCompat="@drawable/icon_cry" />

    <Button
        android:id="@+id/button_paste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Paste"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Button
        android:id="@+id/button_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Back"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_paste" />

</androidx.constraintlayout.widget.ConstraintLayout>
ImageActivity.java
package org.o7planning.clipboarduriexample;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

public class ImageActivity  extends AppCompatActivity {

    private static final String LOG_TAG = "AndroidExample";

    private ClipboardManager clipboardManager;

    private ImageView imageView;
    private Button buttonBack;
    private Button buttonPaste;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);

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

        //
        this.imageView = (ImageView) this.findViewById(R.id.imageView);

        this.buttonPaste = (Button) this.findViewById(R.id.button_paste);
        this.buttonPaste.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doPaste();
            }
        });


        this.buttonBack = (Button) this.findViewById(R.id.button_back);
        this.buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doBack();
            }
        });
    }



    private void doPaste()  {
        Intent intent= this.getIntent();

        ClipData primaryClipData = this.clipboardManager.getPrimaryClip();

        if(primaryClipData == null)  {
            this.imageView.setImageURI(null);
            return;
        }

        ClipData.Item item = primaryClipData.getItemAt(0);

        Uri uri = item.getUri();

        this.imageView.setImageURI(uri);
    }

    // Back to MainActivity.
    private void doBack()  {
        this.finish();
    }

}
Giao diện của MainActivity:
activity_main.xml
<?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/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Select Image (In drawable folder):"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView">

        <RadioButton
            android:id="@+id/radioButton_cry"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="icon_cry.png" />

        <RadioButton
            android:id="@+id/radioButton_feel_good"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="icon_feel_good.png" />
    </RadioGroup>

    <Button
        android:id="@+id/button_copy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Copy Image to Clipboard"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/radioGroup" />

    <Button
        android:id="@+id/button_go"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:text="Go to ImageActivity"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_copy" />

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.xml
package org.o7planning.clipboarduriexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;

import java.util.Date;

public class MainActivity extends AppCompatActivity {

    private static final String LOG_TAG = "AndroidExample";

    private ClipboardManager clipboardManager;

    private Button buttonCopy;
    private Button buttonGo;

    private RadioButton radioButtonCry;
    private RadioButton radioButtonFeelGood;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

        this.radioButtonCry = (RadioButton) this.findViewById(R.id.radioButton_cry);
        this.radioButtonFeelGood = (RadioButton) this.findViewById(R.id.radioButton_feel_good);

        this.buttonCopy = (Button) this.findViewById(R.id.button_copy);
        this.buttonGo = (Button) this.findViewById(R.id.button_go);

        this.buttonCopy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doCopy();
            }
        });

        this.buttonGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToImageActivity();
            }
        });
    }


    private void doCopy()  {
        int resId = R.drawable.icon_cry;

        if(this.radioButtonCry.isChecked()) {
            resId = R.drawable.icon_cry;
        } else if(this.radioButtonFeelGood.isChecked()) {
            resId = R.drawable.icon_feel_good;
        }

        Resources resources = this.getResources();

        // android.resource://org.o7planning.clipboarduriexample/drawable/icon_cry
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE //  android.resource
                + "://" + resources.getResourcePackageName(resId) // org.o7planning.clipboarduriexample
                + '/' + resources.getResourceTypeName(resId)  // drawable
                + '/' + resources.getResourceEntryName(resId); // icon_cry

        Log.i(LOG_TAG, path);

        Uri uriCopy = Uri.parse(path);

        // ClipData (Uri)
        ClipData clipData = ClipData.newRawUri("Some label", uriCopy);

        // Copy ClipData to Clipboard.
        this.clipboardManager.setPrimaryClip(clipData);
    }

    private void goToImageActivity() {
         // Create an Intent:
        Intent myIntent = new Intent(this, ImageActivity.class);

        // Extra data:
        myIntent.putExtra("text1", "This is text1 sent from MainActivity at " + new Date());
        myIntent.putExtra("text2", "This is text2 sent from MainActivity at " + new Date());

        // Start ImageActivity
        this.startActivity(myIntent);
    }
}

Các hướng dẫn lập trình Android

Show More