Remove space between characters

Viewed 102

I am developing a simple calculator using Android Studio.

I have built many buttons that emulate the real keys.

I have set a number for each button.

When hitting the button, can get the text from the button pressed as well as print it to the display area where all numbers will appear.

Everything works well except for the fact that a space appears between numbers when being displayed as shown in the emulator.

What can I do ?

static void getSetText (Button button) {
    String input;

    button.setOnClickListener (new View.OnClickListener() {
        @Override
        public void onClick (View v) {
            Button b = (Button) v;

            buttText = b.getText().toString();

            if (init) {
                display.setText ("");
                init = false;
            }
            display.setText (display.getText() + buttText);
        }
    });
}

EMULATOR:

An image showing the above code side-by-side with an emulated phone screen showing the numbers displayed with a space between them

2 Answers

A simple trimming would do if the cause of issue is an space,

static void getSetText (Button button) {

    String input;


    button.setOnClickListener (new View.OnClickListener() {
        @Override
        public void onClick (View v) {

            Button b = (Button) v;

            buttText = b.getText().toString();

            if (init) {

                display.setText ("");

                init = false;

            }

            display.setText (display.getText().toString().trim() + buttText.trim());

        }

    });

}

But it could also be because of android:letterSpacing in your xml layout. Take a look here regarding this, https://developer.android.com/reference/android/widget/TextView#attr_android:letterSpacing

Remove the blankspace from the String.

static void getSetText (Button button) {

String input;


button.setOnClickListener (new View.OnClickListener() {
    @Override
    public void onClick (View v) {

        Button b = (Button) v;

        buttText = b.getText().toString();

        if (init) {

            display.setText ("");

            init = false;

        }

         display.setText (display.getText().toString().replaceAll(" ","") + buttText.replaceAll(" ",""));
        

    }

});

}
Related