天天看點

Android Api Demos登頂之路(六十)Content-->ClipBoard

這個demo示範了剪貼闆的基本用法。

* 使用流程:

* (1).擷取剪貼闆管理器:ClipboardManager mClipboardManager =

* (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);

* (2).建立能夠存入剪貼闆的ClipData對象(ClipData對象中包含一個或多個ClipData.Item對象):

* A. 建立普通字元型ClipData:ClipData mClipData =

* ClipData.newPlainText(“Label”, “Content”);

* B. 建立URL型ClipData:ClipData.newRawUri(“Label”, Uri.parse(“http://www.fishme.cn/“));

* C. 建立Intent型ClipData:ClipData.newIntent(“Label”, intent);

* 需要注意的是:上面三種方法隻在ClipData對象中建立了一個ClipData.Item對象,

* 如果想向ClipData對象中添加多個Item應該通過ClipData對象的addItem()方法添加。

* (3)将ClipData資料複制到剪貼闆:ClipboardManager.setPrimaryClip(ClipData對象);

* (4)從剪貼闆中擷取ClipData資料:ClipboardManager.getPrimaryClip();

* (5)解析ClipData中的資料

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/copy_style_text"
            android:text="Copy Text"/>
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/style_text"
            android:textStyle="normal"/>
    </LinearLayout>
     <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/copy_plain_text"
            android:text="Copy Text"/>
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/plain_text"/>
    </LinearLayout>
     <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/copy_html"
            android:text="Copy Text"/>
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/html"/>
    </LinearLayout>
     <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/copy_intent"
            android:text="Copy Intent"/>
        <Button 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/copy_uri"
            android:text="Copy Uri"/>
    </LinearLayout>
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_vertical">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Data type:"/>
        <Spinner 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/spinner_datatype"
            android:prompt="@string/clip_type"/>
    </LinearLayout>
    <LinearLayout 
        android:layout_marginTop="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="MIME types:"/>
        <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/clip_mime_type"
            android:background="#88303030"/>
    </LinearLayout>
    <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Data Content:"/>
    <TextView 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/clip_data_content"
            android:background="#88303030"/>

</LinearLayout>
           

array.aml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="clip_data_types">
        <item >No data in clipborad</item>
        <item>Text clip</item>
        <item>HTML Text clip</item>
        <item>Intent clip</item>
        <item>Uri clip</item>
        <item>Coerce to text</item>
        <item>Coerce to styled text</item>
        <item>Coerce to HTML text</item>
    </string-array>
</resources>
           

MainActivity

public class MainActivity extends Activity implements OnClickListener {

    private ClipboardManager mCM;
    private Spinner spinner_data_type;
    private TextView clip_mime_type;
    private TextView clip_data_content;
    private String mHtmlPlainText;
    private OnPrimaryClipChangedListener mClipChangeListener = new OnPrimaryClipChangedListener() {
        @Override
        public void onPrimaryClipChanged() {
            /*
             * Toast.makeText(MainActivity.this, "剪貼闆中的内容變化了!", 0).show();
             */
            updateClipData(true);
        }
    };
    // 注意一定要把styleText(帶格式的文本)定義成CharSequence,而不能定義為String
    private CharSequence styleText;
    private String plainText;
    private String htmlText;

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

        TextView style_text = (TextView) findViewById(R.id.style_text);
        TextView plain_text = (TextView) findViewById(R.id.plain_text);
        TextView html = (TextView) findViewById(R.id.html);
        clip_mime_type = (TextView) findViewById(R.id.clip_mime_type);
        clip_data_content = (TextView) findViewById(R.id.clip_data_content);
        // 在這裡必須要用getText方法,而不能用getString方法,否則得不到帶格式的文本,而且
        // 還會報錯。
        styleText = getText(R.string.style_text);
        style_text.setText(styleText);
        plainText = getString(R.string.plain_text);
        plain_text.setText(plainText);
        htmlText = "<b>Link:</b> <a href=\"http://www.android.com\">Android</a>";
        mHtmlPlainText = "Link: http://www.android.com";
        html.setText(htmlText);

        mCM = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        Button copy_style_text = (Button) findViewById(R.id.copy_style_text);
        Button copy_plain_text = (Button) findViewById(R.id.copy_plain_text);
        Button copy_html = (Button) findViewById(R.id.copy_html);
        Button copy_intent = (Button) findViewById(R.id.copy_intent);
        Button copy_uri = (Button) findViewById(R.id.copy_uri);
        copy_style_text.setOnClickListener(this);
        copy_plain_text.setOnClickListener(this);
        copy_html.setOnClickListener(this);
        copy_intent.setOnClickListener(this);
        copy_uri.setOnClickListener(this);

        spinner_data_type = (Spinner) findViewById(R.id.spinner_datatype);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.clip_data_types,
                android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_data_type.setAdapter(adapter);
        spinner_data_type
                .setOnItemSelectedListener(new OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent,
                            View view, int position, long id) {
                        updateClipData(false);
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                    }
                });

        // 為剪貼闆添加内容變化的監聽
        mCM.addPrimaryClipChangedListener(mClipChangeListener);
        updateClipData(true);
    }

    @Override
    public void onClick(View v) {
        // 根據内容的不同類型構造ClipData資料,并将其複制到剪貼闆
        ClipData clipData = null;
        switch (v.getId()) {
        case R.id.copy_style_text:
            clipData = ClipData.newPlainText("style text", styleText);
            mCM.setPrimaryClip(clipData);
            break;
        case R.id.copy_plain_text:
            clipData = ClipData.newPlainText("plain text", plainText);
            mCM.setPrimaryClip(clipData);
            break;
        case R.id.copy_html:
            // 第二個參數表時當html隻作為普通文本,不處理連接配接請求時的值
            clipData = ClipData.newHtmlText("html text", mHtmlPlainText,
                    htmlText);
            mCM.setPrimaryClip(clipData);
            break;
        case R.id.copy_intent:
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://www.android.com/"));
            clipData = ClipData.newIntent("view intent", intent);
            mCM.setPrimaryClip(clipData);
            break;
        case R.id.copy_uri:
            clipData = ClipData.newRawUri("URI",
                    Uri.parse("http://www.android.com/"));
            mCM.setPrimaryClip(clipData);
            break;
        }
    }

    /**
     * 更新剪貼闆資料
     * 
     * @param updateTypes
     *            :控制下拉清單框是否更新選中的條目
     */
    protected void updateClipData(boolean updateTypes) {
        // 從剪貼闆中取出ClipData資料
        ClipData clip = mCM.getPrimaryClip();
        // 取出與目前設定的Mimetypes比對的ClipData中的所有資料類型,*/*表示任意的類型
        // 即取出目前ClipData中所有的資料類型
        String[] mimeTypes = clip!=null ? clip.getDescription().filterMimeTypes("*/*"):null;
        if (mimeTypes != null) {
            clip_mime_type.setText("");
            for (int i = ; i < mimeTypes.length; i++) {
                if (i > ) {
                    // 因為一個ClipData中可以有多個Item,每個條目的資料類型也不一定相同
                    // 如果有多個資料類型,則在每個資料類型後插入換行
                    // 需要注意的是在本例中隻有一個Item
                    clip_mime_type.append("\n");
                }
                clip_mime_type.append(mimeTypes[i]);
            }
        } else {
            clip_mime_type.setText("NULL");
        }

        // 是否更新下拉清單中的選中條目
        if (updateTypes) {
            if (clip != null) {
                // 隻有一個條目
                ClipData.Item item = clip.getItemAt();
                // 如果剪貼闆中的資料是普通文本則将下拉清單的條一項設定為選中
                //這裡需要注意的是必須先判斷item.getHtmlText()因為如果先判斷item.getText()
                //的話當我們點選Copy Text按鈕複制htmlText文本時就會執行getText方法得到
                //PlainHtmlText,這不是我們想要的結果
                if (item.getHtmlText() != null) {
                    spinner_data_type.setSelection();
                }else if(item.getText()!=null){
                    spinner_data_type.setSelection();
                }else if (item.getIntent() != null) {
                    spinner_data_type.setSelection();
                }else if (item.getUri() != null) {
                    spinner_data_type.setSelection();
                }else {
                    spinner_data_type.setSelection();
                }
            } else {
                spinner_data_type.setSelection();
            }
        }

        if (clip != null) {
            ClipData.Item item = clip.getItemAt();
            switch (spinner_data_type.getSelectedItemPosition()) {
            case :
                clip_data_content.setText("No data");
                break;
            case :
                if (item.getText() != null) {
                    clip_data_content.setText(item.getText());
                } else {
                    Toast.makeText(MainActivity.this,
                            "你所選擇的資料類型與剪貼闆中的資料類型不一緻!", ).show();
                }
                break;
            case :
                if (item.getHtmlText() != null) {
                    clip_data_content.setText(item.getHtmlText());
                } else {
                    Toast.makeText(MainActivity.this,
                            "你所選擇的資料類型與剪貼闆中的資料類型不一緻!", ).show();
                }
                break;
            case :
                if (item.getIntent() != null) {
                    clip_data_content.setText(item.getIntent().toUri());
                } else {
                    Toast.makeText(MainActivity.this,
                            "你所選擇的資料類型與剪貼闆中的資料類型不一緻!", ).show();
                }
                break;
            case :
                if (item.getUri() != null) {
                    clip_data_content.setText(item.getUri().toString());
                } else {
                    Toast.makeText(MainActivity.this,
                            "你所選擇的資料類型與剪貼闆中的資料類型不一緻!", ).show();
                }
                break;
            case :
                clip_data_content.setText(item.coerceToText(this));
                break;
            case :
                clip_data_content.setText(item.coerceToStyledText(this));
                break;
            case :
                clip_data_content.setText(item.coerceToHtmlText(this));
                break;
            }
        } else {
            clip_data_content.setText("Null clip");
        }
        //設定文本的超連結可用
        clip_data_content.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除對剪貼闆内容變化的監聽
        mCM.removePrimaryClipChangedListener(mClipChangeListener);
    }
}
           

繼續閱讀