- Android — Clipboard
- Copying data
- Pasting data
- Example
- Android — буфер обмена
- Копирование данных
- Вставка данных
- пример
- Android Clipboard with Examples
- Android Copying Data to Clipboard
- Android Pasting Data from Clipboard
- Android Clipboard App Example
- activity_main.xml
- MainActivity.java
- Output of Android Clipboard App Example
Android — Clipboard
Android provides the clipboard framework for copying and pasting different types of data. The data could be text, images, binary stream data or other complex data types.
Android provides the library of ClipboardManager and ClipData and ClipData.item to use the copying and pasting framework.In order to use clipboard framework, you need to put data into clip object, and then put that object into system wide clipboard.
In order to use clipboard , you need to instantiate an object of ClipboardManager by calling the getSystemService() method. Its syntax is given below −
Copying data
The next thing you need to do is to instantiate the ClipData object by calling the respective type of data method of the ClipData class. In case of text data , the newPlainText method will be called. After that you have to set that data as the clip of the Clipboard Manager object.Its syntax is given below −
The ClipData object can take these three form and following functions are used to create those forms.
Sr.No | ClipData Form & Method | |||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Sr.No | Method & description | ||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Steps | Description |
---|---|
1 | You will use Android studio IDE to create an Android application and under a package com.example.sairamkrishna.myapplication. |
2 | Modify src/MainActivity.java file to add necessary code. |
3 | Modify the res/layout/activity_main to add respective XML components |
4 | Run the application and choose a running android device and install the application on it and verify the results |
Following is the content of the modified main activity file src/MainActivity.java.
Following is the modified content of the xml res/layout/activity_main.xml.
Following is the content of the res/values/string.xml.
Following is the content of AndroidManifest.xml file.
Let’s try to run our an application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project’s activity files and click Run icon from the tool bar. Android studio installer will display following images −
Now just enter any text in the Text to copy field and then select the copy text button. The following notification will be displayed which is shown below −
Now just press the paste button, and you will see the text which is copied is now pasted in the field of Copied Text. It is shown below −
Источник
Android — буфер обмена
Android предоставляет структуру буфера обмена для копирования и вставки различных типов данных. Данные могут быть текстом, изображениями, данными двоичного потока или другими сложными типами данных.
Android предоставляет библиотеку ClipboardManager, ClipData и ClipData.item для использования среды копирования и вставки. Чтобы использовать структуру буфера обмена, необходимо поместить данные в объект клипа, а затем поместить этот объект в буфер обмена всей системы.
Чтобы использовать буфер обмена, вам нужно создать экземпляр объекта ClipboardManager, вызвав метод getSystemService () . Его синтаксис приведен ниже —
Копирование данных
Следующее, что вам нужно сделать, — создать экземпляр объекта ClipData, вызвав метод данных соответствующего типа из класса ClipData. В случае текстовых данных будет вызван метод newPlainText . После этого вы должны установить эти данные как клип объекта Clipboard Manager. Его синтаксис приведен ниже —
Объект ClipData может принимать эти три формы, и для создания этих форм используются следующие функции.
Sr.No | Форма и метод ClipData | |||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
меры | Описание |
---|---|
1 | Вы будете использовать Android Studio IDE для создания приложения Android и в пакете com.example.sairamkrishna.myapplication. |
2 | Измените файл src / MainActivity.java, чтобы добавить необходимый код. |
3 | Измените res / layout / activity_main, чтобы добавить соответствующие компоненты XML |
4 | Запустите приложение и выберите работающее устройство Android, установите на него приложение и проверьте результаты. |
Ниже приводится содержимое измененного основного файла активности src / MainActivity.java .
Ниже приводится измененное содержимое файла xml res / layout / activity_main.xml .
Ниже приводится содержимое файла res / values / string.xml .
Ниже приводится содержимое файла AndroidManifest.xml .
Давайте попробуем запустить наше приложение, которое мы только что изменили. Я предполагаю, что вы создали свой AVD во время настройки среды. Чтобы запустить приложение из студии Android, откройте один из файлов деятельности вашего проекта и нажмите «Выполнить». значок из панели инструментов. Установщик Android-студии отобразит следующие изображения —
Теперь просто введите любой текст в поле «Текст для копирования» и затем нажмите кнопку «Копировать текст». Будет отображено следующее уведомление, которое показано ниже:
Теперь просто нажмите кнопку вставки, и вы увидите, что скопированный текст теперь вставляется в поле Скопированный текст. Это показано ниже —
Источник
Android Clipboard with Examples
In android, Clipboard is a framework that is useful for copying and pasting the different types of data such as text strings, images, binary stream data, and other complex data types.
Generally, the android Clipboard framework will store the simple text data directly in the clipboard and the complex data is stored as a reference that the pasting application resolves with a content provider.
In android, the clipboard copying and pasting works within an application and between the applications that implement the framework.
To use the android clipboard framework, we need to put the data into a clip object, and then put the clip object on the system-wide clipboard.
The clip object in android can take one of three forms to copy and paste data in android applications.
Clip Data Form | Description |
---|---|
Text | It’s a text string. We can put the string directly into the clip object, and then put the clip object on the clipboard. To paste the string, we can get the clip object from the clipboard and copy the string to our application’s storage. |
URI | It represents any form of URI and it’s primarily for copying the complex data from a content provider. To copy the data, we need to put a Uri object into a clip object, and then put the clip object onto the clipboard. To paste the data, we need to get the clip and Uri objects, resolve it to a data source such as a content provider, and copy the data from the source into our application’s storage. |
Intent | To copy data, we need to create an Intent object, put it into a clip object, and then put the clip object onto the clipboard. To paste the data, we need to get the clip object and then copy the Intent object into our application’s memory area. |
In android, the clipboard can hold only one clip object at a time. When an application puts a clip object on the clipboard, the previous clip object disappears.
To use the clipboard in our applications, we need to create an instance of ClipboardManger class by calling the getSystemService() method.
Following is the syntax of creating an instance of ClipboardManager by calling the getSystemService() method.
If you observe above code snippet, we created an instance of ClipboardManager by calling getSystemService() method.
Android Copying Data to Clipboard
As discussed, to copy the data to clipboard we need to create an instance of ClipData object by calling the respective type of data method of ClipData class. In case if it is text type, then newPlainText method will be called, and add the finished ClipData object to the ClipboardManager object using the setPrimaryClip method.
Following is the code snippet of copying the text data to clipboard in android applications.
ClipboardManager clipboardManager ;
ClipData clipData ;
String txtcopy = «Welcome to tutlane» ;
clipData = ClipData.newPlainText( «text» ,txtcopy);
clipboardManager .setPrimaryClip( clipData );
If you observe above code snippet, we copied text type of data to ClipData object and added ClipData object to the ClipboardManager object using setPrimaryClip method to copy the data to clipboard.
Android Pasting Data from Clipboard
As described previously, you paste data from the clipboard by getting the global clipboard object, getting the clip object, looking at its data, and if possible copying the data from the clip object to your own storage.
As discussed, to paste the data from clipboard we need to create an instance of ClipData object to get the clip data from ClipboardManager object using the getPrimaryClip() method. If data available, get the data from clip data using ClipData.Item object. After that copy its text to your own storage using getText().
Following is the code snippet to pasting the data from the clipboard in android applications.
ClipData pData = clipboardManager .getPrimaryClip();
ClipData.Item item = pData.getItemAt( 0 );
String txtpaste = item.getText().toString();
If you observe above code snippet, we are getting the clip data from ClipboardManager object using getPrimaryClip() method. After that, we are getting the data from ClipData object using ClipData.Item and getText() method.
Now we will see how to use the clipboard for copying and pasting text type data in the android application with examples.
Android Clipboard App Example
Following is the example of copying the text type data into the clipboard from edittext on button click and pasting the clipboard data into another edittext control on button click in android application.
Create a new android application using android studio and give names as ClipboardExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
xml version= «1.0» encoding= «utf-8» ?>
LinearLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :orientation= «vertical» android :layout_width= «match_parent»
android :layout_height= «match_parent» >
TextView
android :id= «@+id/fstTxt»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «150dp»
android :text= «Enter Text to Copy»
/>
EditText
android :id= «@+id/txtCopy»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :text= «Welcome to Tutlane»
android :ems= «10» >
EditText >
Button
android :id= «@+id/btnCopy»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :text= «Copy Data to Clipboard»/>
TextView
android :id= «@+id/secTxt»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :text= «Show Copied Data»
android :layout_marginLeft= «100dp»
/>
EditText
android :id= «@+id/txtShow»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :ems= «10»/>
Button
android :id= «@+id/btnShow»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :text= «Show Clipboard Data»/>
LinearLayout >
Now open your main activity file MainActivity.java from \java\com.tutlane.clipboardexample path and write the code like as shown below
MainActivity.java
package com.tutlane.clipboardexample;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
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 ctxt ;
private EditText ptxt ;
private Button btncpy ;
private Button btnpst ;
private ClipboardManager clipboardManager ;
private ClipData clipData ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
ctxt =(EditText)findViewById(R.id. txtCopy );
ptxt = (EditText)findViewById(R.id. txtShow );
btncpy = (Button)findViewById(R.id. btnCopy );
btnpst = (Button)findViewById(R.id. btnShow );
clipboardManager = (ClipboardManager)getSystemService(Context. CLIPBOARD_SERVICE );
btncpy .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
String txtcopy = ctxt .getText().toString();
clipData = ClipData.newPlainText( «text» ,txtcopy);
clipboardManager .setPrimaryClip( clipData );
Toast.makeText(getApplicationContext(), «Data Copied to Clipboard» , Toast. LENGTH_SHORT ).show();
>
>);
btnpst .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
ClipData pData = clipboardManager .getPrimaryClip();
ClipData.Item item = pData.getItemAt( 0 );
String txtpaste = item.getText().toString();
ptxt .setText(txtpaste);
Toast.makeText(getApplicationContext(), «Data Pasted from Clipboard» ,Toast. LENGTH_SHORT ).show();
>
>);
>
>
If you observe above code snippet, we used ClipboardManager, ClipData, ClipData.Item objects to copy a data into clipboard and paste a data from clipboard based on our requirements.
Output of Android Clipboard App Example
When we run above program in android studio we will get the result like as shown below.
If we enter text in the first edittext and click on Copy Data to Clipboard button, the text will be copied to the clipboard and when we click on Show Clipboard Data, the clipboard data will be pasted into second edittext control.
This is how we can use clipboard framework in android applications to copy and paste the data based on our requirements.
Источник