감성 자동제어
[안드로이드 스튜디오]버튼 클릭시 이미지를 변경하자
안녕하세요! 오늘은 버튼을 클릭했을 때 이미지를 변경하는 방법대한 글을 작성하겠습니다!!
drawable 파일에 이미지 추가
1. 2개의 이미지 파일을 준비해서 drawable에 추가 시켜줍니다!(드래그 앤 드랍으로 추가 가능)
2. 파일의 이름을 사용자의 편의에 맞추어 지어줍니다!

Activity_main.xml(layout)
이미지뷰 하나와 버튼하나를 만들어 주도록 하겠습니다!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="3"
android:src="@drawable/baby_lion" />
<Button
android:id="@+id/bnt_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_weight="0.5"
android:text="이미지 바꾸기"
android:textSize="30dp" />
</LinearLayout>
|
cs |
MainActivity(Class)
boolean값 변수를 지정해서 "true"와 "false"를 이용하여 이미지를 바꾸어 주도록 하겠습니다!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
Button m_btn;
ImageView imageView;
boolean i = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_btn = findViewById(R.id.bnt_image);
imageView = findViewById(R.id.image_view);
m_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (i == true){
imageView.setImageResource(R.drawable.adult_lion);
i = false;
}else {
imageView.setImageResource(R.drawable.baby_lion);
i = true;
}
}
});
}
}
|
cs |
마무리
이상으로 버튼을 클릭해서 이미지를 바꾸는 방법에 대해 알아보았습니다! 3개 이상의 이미지를 번갈아 가며 바꾸는 실습도 한번 해보신다면 더욱 좋을것 같습니다! 감사합니다!!
'안드로이드 스튜디오' 카테고리의 다른 글
[안드로이드 스튜디오] XML을 이용한 옵션메뉴 만들기! (0) | 2020.11.25 |
---|---|
[안드로이드 스튜디오] 대화상자(dialog) 사용하는 방법-AlertDialog (0) | 2020.11.23 |
[안드로이드 스튜디오] 버튼클릭시 홈페이지 열기!(Intent) (0) | 2020.11.18 |
[안드로이드 스튜디오] 버튼클릭시 토스트 메시지 띄우기 (0) | 2020.11.17 |
[안드로이드 스튜디오] 버튼 클릭으로 화면전환하자!(Intent) (0) | 2020.11.16 |