반응형

Android에서 버튼의 색상을 눌렀을 때와 같이 상태에 따라 변경 시키고 싶다면 ColorStateList를 활용하면 된다. 

 

배경 이미지를 바꾸는 것과 비슷하다.

 

color selector는 별도의 color 리소스 폴더를 만들어 관리한다.

 

 

MainActivity.java

package com.demo.testing;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        button.setTextColor(getResources().getColorStateList(R.color.selector_option, null));
    }
}

 

selector_option.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:color="#123123"/>
    <item android:state_focused="true"
        android:color="#ff1122"/>
    <item android:color="#abc112"/>
</selector>

 

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="100dp"
        android:layout_height="50dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:text="click"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

 

반응형