안드로이드 코틀린
[Kotlin][Android] 복합 대입 연산자 활용하기
teamnova
2025. 2. 25. 23:28
728x90
오늘은 복합 대입 연산자를 활용해 더하기, 곱하기, 빼기 값을 화면에 보이게하는 예시를 만들어 보겠습니다.
레이아웃 xml 파일 코드(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<!-- 점수를 보여줄 텍스트뷰 -->
<TextView
android:id="@+id/ScoreView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="점수: 0"
android:textSize="24sp" />
</LinearLayout>
액티비티 코틀린 코드
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 텍스트뷰를 가져오기
val ScoreView = findViewById<TextView>(R.id.ScoreView)
// 점수를 나타내는 변수 (초기값 0)
var score = 0
// 복합 대입 연산자를 활용해 점수 증가 처리
score += 10 // score = score + 10
// 텍스트뷰의 텍스트 갱신
ScoreView.text = "점수: $score"
// 곱하기 처리
score *= 2 // score = score * 2
ScoreView.append("\n곱하기 2 이후: $score")
// 빼기 처리
score -= 5 // score = score - 5
ScoreView.append("\n빼기 5 이후: $score")
}
}
실행 결과 화면
위 이미지 처럼 복합 대입 연산자를 활용해 더하기, 곱하기, 빼기 값이 정상적으로 보이는 것을 확인할 수 있습니다