繁体   English   中英

重复文本在TextView中给按钮施加压力

[英]Repeated text in the TextView to the pressure of the Button

我有按一下按钮即可执行的代码。

 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的文本为“ Example”,text03的“ Example2”和text05的“ Example3”,并且我在按钮上按了两次,则结果为

示例示例2示例3示例示例2 example3

为什么? 我该如何解决?

您需要使用TextView.setText("parameter")代替TextView.append();

考虑到您正在使用append方法,该方法将在每次按下按钮时不断添加文本,这些结果令我并不感到惊讶。 如果只想添加一次文本,则需要某种方式来跟踪已按下哪个按钮或已向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的文本仅设置为该字符串,而不会伴随其他按钮的额外按下,而这正是查看您的示例代码所要做的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM