我有这样的代码,只要按一下按钮就可以执行。
Button myButton = (Button) view.findViewById(R.id.button01);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
class = new MyClass();
class.Method();
if(class.Method()) {
TextView.append(Html.fromHtml((getString(R.string.text01))));
}
else {
TextView.append(Html.fromHtml((getString(R.string.text02))));
}
try {
if (class.Method2() && (class.Method3()))
{
TextView.append(Html.fromHtml((getString(R.string.text03))));
}
else {
TextView.append(Html.fromHtml((getString(R.string.text04))));
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(class.Method4()) {
TextView.append(Html.fromHtml((getString(R.string.text05))));
}
else {
TextView.append(Html.fromHtml((getString(R.string.text06))));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});如果方法返回true,并且按下该按钮两次或更多次,则根据按该按钮的次数,在TextView中显示多次重复的文本。
因此,如果text01的文本是“示例”、text03 "Example2“和text05 "Example3”,并且我在按钮上按了两次,结果是
示例Example2 example3示例Example2 example3
为什么?我怎么才能修好?
发布于 2013-09-27 14:33:28
考虑到您使用的是追加方法,每次按按钮时都会追加文本,我对这些结果并不感到惊讶。如果只想添加文本一次,则需要某种方式来跟踪按下哪个按钮或向TextView添加了哪些文本。取决于您有多少个按钮,一个按钮可能比另一个按钮容易。
我将使用一个普通字符串来连接文本,而不是追加。看起来你用的是固定字符串。这意味着应该很容易检查您添加的内容和没有添加的内容。我可能会做这样的事
String concatResult = "";
//button onClick set up goes here
if(class.Method()){
String stringToAdd = getStringFromResources(); //get appropriate string
if(!concatResult.contains(stringToAdd){
concatResult += stringToAdd;
}
}
//when you're done with the tests for which string to add
textView.setText(concatResult);您将不得不使用所添加内容的间距(我不知道文本是如何格式化的),但是这种方法应该允许您在按下每个按钮时添加一次文本。仅在每个条件中使用setText将只将TextView文本设置为该字符串,它不会限制其他按钮的附加按下,而查看示例代码就是您想要做的。
发布于 2013-09-27 14:26:13
您需要使用TextView.setText("parameter")而不是TextView.append();
https://stackoverflow.com/questions/19052766
复制相似问题