我有多个不同标题和内容的cardView。我想在按下按钮时仅复制内容。这是适配器类中的ViewHolder。
TextView title;
TextView content;
Button copyButton;
public ViewHolder(View itemView) {
super(itemView);
this.title = (TextView)itemView.findViewById(R.id.card_title);
this.content = (TextView)itemView.findViewById(R.id.card_content);
this.copyButton= (Button)itemView.findViewById(R.id.copyButton);
并在onBindViewHolder buttonClickListener中我这样做了:
holder.copyButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
myClipboard = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
myClip = ClipData.newPlainText("text",v.content.getText().toString() );
myClipboard.setPrimaryClip(myClip);
Toast.makeText(v.getContext(), "Copied to clipboard" , Toast.LENGTH_SHORT ).show();
}
});
但它不接受这个'v.content.getText()。toString()'我该怎么办?
答案 0 :(得分:0)
View v是对按钮的引用,而不是TextView的标题和内容。你需要做这样的事情来获取你在onClick方法中寻找的文本:
string title = ViewHolder.this.title.getText();
string content = ViewHolder.this.content.getText();
holder.copyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// v is equal to copyButton, not an instance of ViewHolder
// v.content doesn't exist because the copyButton doesn't have a content property
// ViewHolder.this is equal to holder and contains the TextView content which you are trying to get the text from
string content = ViewHolder.this.content.getText().toString();
}
}