Android

Android Studio - TextView의 setText 함수에서 쉽게 숫자를 문자열로 변경하기

Cong_S 2022. 7. 8. 18:09

유저가 숫자를 입력했을 때, 현재 년도를 calendar 클래스에서 데이터를 가져와 

차이를 구해 화면에 출력하는 코드이다.

public class MainActivity extends AppCompatActivity {

    EditText editYear;
    Button button;
    TextView textAge;

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

        editYear = findViewById(R.id.editYear);
        button = findViewById(R.id.button);
        textAge = findViewById(R.id.textAge);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 1. 유저가 입력한 년도를 가져온다.
                String yearStr = editYear.getText().toString();

                // 1-1. calendar 클래스로 현재 년도를 가져온다.
                int now = Calendar.getInstance().get(Calendar.YEAR);
//                int now = Calendar.getInstance().get(Calendar.YEAR);

                //1-2. 문자열을 int 로 변환.
                int year = Integer.valueOf(yearStr).intValue();

                // 2. 현재 년도와 계산한다.
                //    현재 년도 - 유저가 입력한 년도
                int Age = now - year;


                // 3. 나이를 화면에 표시한다.
                textAge.setText(Age+" 살 입니다.");

            }
        });

    }
}

마지막에 textView에 표시될 데이터를 구할 때,

입력된 Age 데이터는 엄연히 int 데이터 이므로 setText로 입력되지 않는 것이 정상이다.

 

아주아주 쉽게 변경하는 방법은 다음과 같다.

textAge.setText("" + Age);

바로 빈 따옴표로 문자열을 더해주는 방법이다. 

이는 빈 따옴표가 아니고

textAge.setText(Age+" 살 입니다.");

다음과 같이 문장이어도 문자열만 붙어주면 문제없이 작동한다.