【问题标题】:How to append text to a TextView after setText()?如何在 setText() 之后将文本附加到 TextView?
【发布时间】:2016-04-20 09:27:44
【问题描述】:

这是我的计算器应用程序的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;
        }
    }
}

【问题讨论】:

    标签: java android textview buttonclick


    【解决方案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; 
            } 
        } 
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多