XML 이 아니라 액티비티에서 텍스트 및 버튼 색상을 변경하는 경우는 대체로 특정 상황마다 색상을 다르게 쓰고 싶을 때이다. JAVA 코드로 액티비티에서 색상을 변경해보자!
1. 텍스트 색상 변경하기
텍스트 색상을 변경하는 건 색상 값을 얼마나 많이 바꿀 거냐에 따라 크게 2가지 방법이 있다.
일단 텍스트 객체를 먼저 가져오자.
// 색상을 변경할 텍스트 객체 가져오기
TextView textView = findViewById(R.id.textView);
첫 번째. 리소스에서 가져온 색상 값을 여러 번 사용할 경우
// 가져온 색상 값을 텍스트 객체에 적용
textView.setTextColor(ContextCompat.getColor(this, colorNameValue));
두 번째. 리소스에서 가져온 색상 값을 한 번만 사용할 경우
// 원하는 색상 값을 텍스트 객체에 바로 적용 (한 번만 사용할 경우)
textView.setTextColor(ContextCompat.getColor(this, R.color.colorName));
2. 버튼 색상 변경하기
2-1. 버튼이 기본 상태일 때, 활성화됐을 때, 눌렸을 때에 따라 색상을 다르게 하고 싶은 경우
이 경우에는 XML 코드와 JAVA 코드를 함께 써주어야 한다.
XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<!-- click -->
<item android:state_pressed="true">
<shape>
<!-- 배경 -->
<solid android:color="@color/pressed" />
<!-- 모서리 -->
<corners
android:bottomLeftRadius="23dp"
android:bottomRightRadius="23dp"
android:topLeftRadius="23dp"
android:topRightRadius="23dp" />
</shape>
</item>
<!-- active -->
<item android:state_enabled="true">
<shape>
<!-- 배경 -->
<solid android:color="@color/active" />
<!-- 모서리 -->
<corners
android:bottomLeftRadius="23dp"
android:bottomRightRadius="23dp"
android:topLeftRadius="23dp"
android:topRightRadius="23dp" />
</shape>
</item>
<!-- default -->
<item android:state_enabled="false">
<shape>
<!-- 배경 -->
<solid android:color="@color/default2" />
<!-- 모서리 -->
<corners
android:bottomLeftRadius="23dp"
android:bottomRightRadius="23dp"
android:topLeftRadius="23dp"
android:topRightRadius="23dp" />
</shape>
</item>
</selector>
이건 내가 임시로 만든 모서리가 약간 둥근 버튼의 xml이다. 기본적으로 비활성화되어 있는 버튼인데, 활성화 시켜줬을 때와 눌릴 때 색상이 바뀐다.
values/color.xml 에서 색상을 지정해주면 편하다.
JAVA
// 버튼 객체 선언
button buttonNameValue = findViewById(R.id.buttonName);
// 버튼의 상태 변경
buttonNameValue.setEnabled(true);
buttonNameValue.setEnabled(false);
buttonNameValue.setChecked(true);
buttonNameValue.setChecked(false);
buttonNameValue.setPressed(true);
buttonNameValue.setPressed(false);
이런 식으로 버튼의 상태를 변경해주면 그에 따라 색상도 변경된다.
어떻게 사용할 것인지에 따라 버튼의 상태를 지정해주면 된다.!
3. 이미지 변경
JAVA
imageView.setImageResource(R.drawable.파일이름);
자신의 코드에 따라 다르게 사용하도록 하자!