在ListView
的行上使用Button,并且能够创建单行Spannable和来自数据库的数据,但是当我点击它时返回整个字符串而不是单词来自MyAdapter Class
我的代码从数据库输入值Listview
public View getView(int i, View view, ViewGroup viewGroup) {
Realm realm=Realm.getDefaultInstance();
Word toEdit = realm.where(Word.class)
.equalTo("id", 10).findFirst();
int id_to_seperate=toEdit.getLang();
LayoutInflater inflater= (LayoutInflater) Main.context.getSystemService(Main.context.LAYOUT_INFLATER_SERVICE);
View row= inflater.inflate(R.layout.layout,viewGroup,false);
TextView word= (TextView) row.findViewById(R.id.word_name);
TextView meaning= (TextView) row.findViewById(R.id.word_define);
Word temp=list.get(i);
int idz=temp.getId();
word.setText(temp.getWord());
if(id_to_seperate==idz){
String span[] = temp.getMeaning().substring(1).split(" ") ;
SpannableString ss = new SpannableString(temp.getMeaning().substring(1));
ClickableSpan spans[] = new ClickableSpan[span.length];
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new ClickableSpan() {
@Override
public void onClick(View textView) {
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
Log.d("View" , text);
}
};
}
int start = 0 ;
int end =0;
try {
for(int spanCount = 0 ; spanCount <span.length ; spanCount++){
if(spanCount==0) {
end += span[spanCount].length();
}else{
end += span[spanCount].length()+1;
}
ss.setSpan(spans[spanCount], start, end , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
start += span[spanCount].length()+1;
}
} catch (Exception e) {
e.printStackTrace();
}
meaning.setText(ss);
meaning.setMovementMethod(LinkMovementMethod.getInstance());
}else {
meaning.setText(temp.getMeaning().substring(1));
}
return row;
}
我能够从列表中的特定行获得结果 这个但是点击功能返回整个句子而不是一个单词或单词,如果有人能告诉我我做了什么错误,我会很感激 此致
答案 0 :(得分:1)
你的代码中出现了错误
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
TextView.getText()。toString()返回全文。如果您想获得具体的ClickableSpan
,请使用以下ClickableSpan
public class SpecialClickableSpan extends ClickableSpan {
String text;
public SpecialClickableSpan(String text){
super();
this.text = text;
}
@Override
public void onClick(View widget) {
Log.d(TAG, "onClick [" + text + "]");
}
}
替换
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new ClickableSpan() {
@Override
public void onClick(View textView) {
TextView v = (TextView)textView ;
String text = v.getText().toString() ;
Log.d("View" , text);
}
};
}
<强>与强>
for(int spanCount = 0 ; spanCount < span.length ; spanCount++){
spans[spanCount] = new SpecialClickableSpan (span[spanCount ]);
}