我在显示附加单词和通过单击 gridview 中选定的 onitem 删除字符串单词值时遇到问题。
我想要这样:
___________
| |
| hello | = hello (CLICK)
|___________|
___________
| |
| hello | = (UNCLICK)
|___________|
例如:如果我单击项目按钮 hello ,它将在 TextView 中显示 "hello" ,当我单击项目按钮 world 时,它将在中显示 "hello world" TextView ,但如果我再次单击项目按钮 hello,它将删除 TextView 中的 hello,如下所示 "world"
这是我的 onitemselect 代码:
ll.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
if(position < noOfBtns) {
String selectedItem = parent.getItemAtPosition(position).toString();
String s2 = text_quiz.getText().toString();
String [] s2_word = s2.split("\\s");
List<String> str = Arrays.asList(s2_word);
if(str.contains(selectedItem))
{
if(str.equals(selectedItem)) {
v.setBackgroundResource(R.drawable.btn_background);
String rep = text_quiz.getText().toString().replace("\\b" + selectedItem + "\\b" + " ", "");
String textToBeColored = "_";
String htmlText = rep.replace(textToBeColored, "<font color='#6B3074'>" + textToBeColored + "</font>");
text_quiz.setText(Html.fromHtml(htmlText));
}
}else {
v.setBackgroundResource(R.drawable.buttons4);
text_quiz.append(selectedItem + " ");
}
}
}
});
在我的代码中,我尝试将 Textview 中的相同选定项目替换为空白,但是当按钮具有相同的单词时,它将不再显示。就像单词you和your一样,替换方法会找到相同的单词并替换它,如果我有一个按钮项目单词a它不会显示代码,它将替换 TextView 中的所有字母 a..
我真的需要帮助
最佳答案
在较高的层面上,根据您所拥有的,您可以:
if (str.remove(selectedItem)) {
// We know selectedItem was removed (the first, not sure if you have multiple)
// so now we can just rebuild (here is a non stream version)
StringBuilder sb = new StringBuilder();
for (String st : str) {
sb.append(textToBeColoured(str)); // Do whatever you want for whichever text
}
textQuiz.setText(Html.fromText(sb.toString());
} else {
// Add like normal
}
您需要按照您想要的方式管理 HTML 突出显示功能,也许更改 for 以包含索引或其他内容。但至少在这个if()
阻止你知道List<String> str
已删除您的文字。
关于java - 如何删除插入到 TextView 的附加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61821001/