반응형
버튼 클릭시 숫자가 증감하는 간단한 로직을 구현해보자. 심심풀이로 올리는 포스팅이니 가볍게 보시길 바란다.
-예제-
-코드-
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingTop="200dp">
<TextView
android:id="@+id/tv_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0"
android:textSize="50sp"
android:gravity="center"
tools:layout_editor_absoluteX="196dp"
tools:layout_editor_absoluteY="232dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="100dp">
<Button
android:id="@+id/btn_add"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="증가"
tools:layout_editor_absoluteX="79dp"
tools:layout_editor_absoluteY="461dp" />
<Button
android:id="@+id/btn_minus"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="감소"
tools:layout_editor_absoluteX="252dp"
tools:layout_editor_absoluteY="461dp" />
</LinearLayout>
</LinearLayout>
MainActivity.java
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button btnAdd, btnMinus;
private TextView tvCount;
private int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvCount = findViewById(R.id.tv_count);
tvCount.setText(count+"");
btnAdd = findViewById(R.id.btn_add);
btnMinus = findViewById(R.id.btn_minus);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
count++;
tvCount.setText(count+"");
}
});
btnMinus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
count--;
tvCount.setText(count+"");
}
});
}
}
반응형
'Android' 카테고리의 다른 글
Android / Retrofit2 사용하기 (0) | 2020.07.29 |
---|---|
Android / 간단한 계산기 앱 만들기 (0) | 2020.07.22 |
Android/ ProgressBar (0) | 2020.07.22 |
Android/ AppCompat위젯으로 버튼 생성하고 클릭 이벤트 주기 (0) | 2020.07.22 |
Android / ScrollView (0) | 2020.07.21 |