1

I'm trying to make a simple calculator in Android Studio, and I'm having trouble repeating the same number in text view.

For example, if I press 1 on the calculator, it will show the number 1 on top, but if I press it again, nothing happens.

Therefore, I can't make numbers greater than 9.

Here's my code:

public class MainActivity extends AppCompatActivity {

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

        Button btn = findViewById(R.id.button0);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView tv = findViewById(R.id.textView);
                tv.setVisibility(view.VISIBLE);
                tv.setText("0");
            }
        });

        btn = findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView tv = findViewById(R.id.textView);
                tv.setVisibility(view.VISIBLE);
                tv.setText("1");
            }
        });
    }
}

3 Answers3

3

Using textViewObj.setText("1"); will always replace the existing text in the view. Based on your description of the requirement, textViewObj.append("1"); should be the one which can achieve it.

Replace textViewObj.setText("1"); with textViewObj.append("1"); appropriately, as follows

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            TextView tv = findViewById(R.id.textView);
            tv.setVisibility(view.VISIBLE);
            tv.append("1");
        }
    });
Sagar
  • 23,903
  • 4
  • 62
  • 62
0

btn is the button you clicked:

btn.setOnClickListener((view)->{
String currentNumber = txtViewObj.getText().toString();
String number =  ((TextView)view).getText().toString(); //I assume that you already named each button corresponding to its number, for example button1 call it 1, button2 call it 2
txtViewObj.setText(currentNumber+number);
});
Alan Deep
  • 2,037
  • 1
  • 14
  • 22
0

Actually what exactly happens is that using textView.setText("1") each time will destroy the TextView's buffer containing any text and simply replace it with the new text i.e. "1" and using textView.append("1") will update the buffer of the TextView to display the concatenated text. Refer to this answer for more details.

Sudhanshu Vohra
  • 1,345
  • 2
  • 14
  • 21