簡體   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