본문 바로가기
App Programming/Android Studio

[Android Studio] 버튼 클릭시 버튼 색상 변경

by goatlab 2022. 11. 21.
728x90
반응형
SMALL

버튼 클릭시 버튼 색상 변경

 

버튼을 터치했을 때 버튼 색상을 변경하는 이벤트를 구현 가능하다.

 

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/buttonEvent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button Event"
        android:textSize="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

java

 

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button buttonEvent;

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

        buttonEvent = (Button)findViewById(R.id.buttonEvent);
        buttonEvent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    buttonEvent.setBackgroundColor(Color.RED);
                } else if(motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    buttonEvent.setBackgroundColor(Color.rgb(0,255,0));
                }
                else{
                    buttonEvent.setBackgroundColor(Color.BLUE);
                }
                return false;
            }
        });
    }
}
코드 기능
setBackgroundColor() 색상 선택
motionEvent.getAction() == MotionEvent.ACTION_DOWN 버튼을 눌렀을 때
motionEvent.getAction() == MotionEvent.ACTION_UP 버튼을 눌렀다가 뗐을 때

기본
눌렀을 때
누르고 움직일 때

728x90
반응형
LIST