如何使用android中的上下文菜单将textview值从listview项复制到剪贴板?

时间:2017-02-17 12:38:17

标签: android listview baseadapter

我想使用列表视图项目中的按钮单击将listview项目中的textview值复制到剪贴板。我可以从listview onitemclick上的listview项中获取textview值。但我想使用上下文菜单获取此值。那么,我如何从listview项中获取值。我在Holder课程中有textview。这是我的代码:

    public View getView(final int position, View convertView, ViewGroup parent) {
            View v = convertView;
            final ViewHolder holder;
            LayoutInflater li = getActivity().getLayoutInflater();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);

            if (v == null) {
                holder = new ViewHolder();
                v = inflater.inflate(R.layout.single_row, parent, false);
                holder.favourit_style = (ImageView) v.findViewById(R.id.favourit_style);
                holder.share_style = (ImageView) v.findViewById(R.id.share_style);
                holder.textView = (TextView) v.findViewById(R.id.text_Style);
                v.setTag(holder);
            } else {
                holder = (ViewHolder) v.getTag();
            }

            editText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    holder.textView.setText("" + s.toString() + "");

                }
            });
            registerForContextMenu(holder.share_style);
            return v;
        }

public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case COPY:
            ViewHolder h = new ViewHolder();
            String s = h.textView.getText().toString();
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setText(s);
            } else {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", s);
                clipboard.setPrimaryClip(clip);
            }
            break;
   return super.onContextItemSelected(item);
}

1 个答案:

答案 0 :(得分:0)

首先,您必须获取要复制的String内容。我认为你可以自己管理。现在,您可以使用以下代码将该内容复制到剪贴板:

android.content.ClipboardManager clipboard = (android.content.ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Clip", textToCopy);
clipboard.setPrimaryClip(clip);
希望能帮到你!