如何在setText()之后将文本追加到TextView?

时间:2016-01-14 21:24:04

标签: java android textview buttonclick

这是我的计算器应用程序的MainActivity,我首先尝试setText(),然后附加到TextView main

我的问题是append()确实有效,但在我调用setText()方法后它只会追加一次。我希望它多次附加文本。

我该怎么做?

public class MainActivity extends Activity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculator_screen);

        TextView main = (TextView) findViewById(R.id.maintextView);
        main.setText("0.");

        Button btnSeven = (Button) findViewById(R.id.btnseven);
        btnSeven.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
       switch(view.getId()) {
           case R.id.btnseven:
               TextView main = (TextView) findViewById(R.id.maintextView);
               main.setText("");
               main.append("7");
               break;
           default :
               break;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

问题是您通过执行以下操作重置TextView上的文本:

main.setText("");

在执行追加操作之前。以下是您的代码应该是什么样的:

public class MainActivity extends Activity implements OnClickListener {

    private TextView mMain;

    @Override 
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculator_screen);

        mMain = (TextView) findViewById(R.id.maintextView);
        mMain.setText("0");

        Button btnSeven = (Button) findViewById(R.id.btnseven);
        btnSeven.setOnClickListener(this);
    } 

    @Override 
    public void onClick(View view) {
        String mainText = mMain.getText().toString();
        try {
            // By parsing the text as a number, you make sure you handle the cases where the user added input like "0." too, so you don't have to handle each and every case with Strings and with if-else statements.
            double actualNumber = Double.parseDouble(mainText);
            if (actualNumber == 0) {
                mMain.setText("");
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            // Something went wrong while parsing. Usually happens because the EditText contains other characters the digits or "."
        }

        switch(view.getId()) {
            case R.id.btnseven:
                mMain.append("7");
                break; 
            default : 
                break; 
        } 
    } 
}