Search code examples
androidstringbuttonnumpad

How to create a NumberPad


I am trying to create a simple number Pad. I am getting the information to the TextView just fine BUT each time I click on a new Button it removes the old one. How do I keep what was in the TextView and add what is new. You push 1 it goes to TextView, You push two it goes to TextView but removes the "1" that was in there before. I want "1" to stay so when you push both button you have 12.

final TextView singlevalue = (TextView) findViewById(R.id.priceInput);
one.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        final Button one = (Button) findViewById(R.id.one);
        final String stringone = one.getText().toString();
        singlevalue.setText(String.valueOf(stringone);
    }
});

I know something like this +"" goes after (stringone) but what???

two.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        final Button two = (Button) findViewById(R.id.two);
        final String stringtwo = two.getText().toString();
        singlevalue.setText(String.valueOf(stringtwo)+"");
    }
});

Solution

  • you need to take one variable globally and add the new entered value when button clicked

    ex say

    public String totalString = "";
    
    
    final TextView singlevalue = (TextView) findViewById(R.id.priceInput);
    one.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            final Button one = (Button) findViewById(R.id.one);
            final String stringone = one.getText().toString();
            totalString = totalString+""+stringone ;
            singlevalue.setText(totalString);
        }
    });
    
    two.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            final Button two = (Button) findViewById(R.id.two);
            final String stringtwo = two.getText().toString();
            totalString = totalString+""+stringtwo ;
            singlevalue.setText(totalString);
        }
    });