Android 剪切板

Android 剪切板,用系統的剪切板,復制剪切操作就要用到它

需求:分享中復制鏈接地址的功能

例子的效果圖,如果隻是簡單的復制文本信息,還是挺簡單的!雖然簡單也分享一下,記錄一下

這裡寫圖片描述


來來來,上代碼瞭。很簡單而已

主要是這個類 ClipboardManager ,中文意思就是剪切板的管理者,如果要進行復制剪切操作就要用到它

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_text;
    private TextView tv_copy;
    private TextView tv_paste;
    private EditText et_show;
    private String air = "";

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

        tv_text = (TextView) findViewById(R.id.tv_text);
        tv_copy = (TextView) findViewById(R.id.tv_copy);
        tv_paste = (TextView) findViewById(R.id.tv_paste);
        et_show = (EditText) findViewById(R.id.et_show);

        tv_copy.setOnClickListener(this);
        tv_paste.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_copy://復制
                air = tv_text.getText().toString().trim();

                //ClipboardManager中文意思就是剪切板的管理者,如果要進行復制剪切操作就要用到它
                //系統剪切板的調用服務
                ClipboardManager copy = (ClipboardManager) getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
                copy.setText(air);
                Toast.makeText(getApplicationContext(),"內容已成功復制到\n粘貼板",Toast.LENGTH_SHORT).show();
                break;
            case R.id.tv_paste://粘貼
                ClipboardManager plaster = (ClipboardManager) getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
                if (plaster.hasText()) {
                    String content = plaster.getText().toString().trim();
                    et_show.setText(content);
                    Toast.makeText(getApplicationContext(), "粘貼成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(getApplicationContext(), "粘貼版沒數據", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

activity_main.xml




    
    

    

    

    

You May Also Like