728x90
안녕하세요.
이번에는 안드로이드스튜디오에서 제공하는 Color.rgb() 라는 유용한 메서드를 사용해서 색상을 무작위로 변경하는 기능을 만들어보겠습니다.
우선 전체 코드입니다.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#FFFFFF">
<Button
android:id="@+id/changeColorButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="배경색 바꾸기" />
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private View rootLayout;
private Button changeColorButton;
private final Random random = new Random(); // 랜덤 객체
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootLayout = findViewById(R.id.root_layout);
changeColorButton = findViewById(R.id.changeColorButton);
changeColorButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// RGB 각각 0~255 사이의 값 생성
int r = random.nextInt(256);
int g = random.nextInt(256);
int b = random.nextInt(256);
int color = Color.rgb(r, g, b); // Color 객체 생성
rootLayout.setBackgroundColor(color); // 배경색 적용
}
});
}
}
Color.rgb(r, g, b) 를 사용해서 rgb 값으로 색상을 생성하여 무작위로 배경색상을 변경해봤습니다.
이것을 활용하여 다양한 색상을 앱에 적용해보고, 확장해보면 좋겠습니다.
시연 영상입니다.
'안드로이드 자바' 카테고리의 다른 글
| [Java][Android]ViewModel, LiveData, Repository 순서 추적하기 (3) | 2025.08.14 |
|---|---|
| [Java][Android] 안드로이드 앱에서 특정 값을 전역으로 사용하기: BuildConfig (2) | 2025.08.02 |
| [Java][Android] Shared Element Transition 사용하여 화면전환 (2) | 2025.07.21 |
| [Java][Android] AnimationDrawable 로 간단한 프레임 애니메이션 만들기 (1) | 2025.07.20 |
| [Java][Android] GestureDetector로 제스처 감지하기 (1) | 2025.07.19 |