Category Archives: android/Kotlin

안드로이드 버튼 background color정보 가져오는 방법

안드로이드 버튼 정보 중에 background를 컬러를 셋팅(setBackgroundColor)하는건 정말 쉬운데,
버튼의 backgroudcolor를 가져오는게 너무 힘들었다.

구글검색, stackoverflow검색 등등 여러가지를 시도해보다가 겨우 방법을 찾아서 내용을 남겨둔다.

찾기 힘들었던 이유 중에 대부분은 안드로이드가 java에서 kotlin으로 바뀌고, 중간중간에 안드로이드가 업데이트되면서 기존에 잘 사용하던 방법이 더이상 안되는 것때문에 방법을 찾는게 너무 힘들었다.

검색하면 나오는 가장 큰 솔루션 중에 themes.xml에 style parent속성이 Theme.AppCompat.Light 로 바뀌는건 이미 되어 있었기 때문에 정답이 아니었다.

두번째로 레이아웃.xml에서 android.widget.Button로 변경하는건, 변경을 해도 동일한 문제가 발생했다.

내가 찾은 방법은 버튼 background정보를 Drawable 클래스로 받아서, 각 클래스(ColorDrawable,StateListDrawable,GradientDrawable,ColorDrawable)에 맞게 color정보를 가져와서 사용하도록 했다.
처음에는 어느 Drawable클래스로 받아야 될지 몰라서 삽질을 계속 했는데, 결국 아래와 같은 처리방법을 찾아서 사용했더니 버튼의 backgroundcolor정보를 접근할 수 있었다.
color정보를 가져오면 기본이 int형 변수인데, 이걸 형변환하면 rgb string값으로 가져올 수 있다.(형변환참고: val hexColor = String.format(“#%06X”, color2))

Kotlin소스코드
private fun startAnimation(bt: android.widget.Button) : Unit {
        val drawable : Drawable = bt.background
        var rtnColor = 0    // 기존버튼의 색을 담을 변수
        when (drawable) {
            is ColorDrawable -> {
                val color = drawable.color
                Log.d(tagName, "startBingoAnimation ColorDrawable color:$color")
                rtnColor = color
            }
            is StateListDrawable -> {
                val drawable2 = drawable?.getStateDrawable(0) //as StateListDrawable
                when (drawable2) {
                    is ShapeDrawable -> {
                        val color = drawable2.paint.color
                        Log.d(tagName, "startBingoAnimation ShapeDrawable color:$color")
                        rtnColor = color
                    }

                    is GradientDrawable -> {
                        val color: ColorStateList? = drawable2.color
                        val color2: Int = color!!.defaultColor
                        Log.d(tagName, "startBingoAnimation GradientDrawable color:${color2}")
                        //val colorStr = color2?.toString(16)
                        val hexColor = String.format("#%06X", color2)
                        //Log.d(tagName, "startBingoAnimation GradientDrawable hexColor:${hexColor}")
                        Log.d(tagName, "startBingoAnimation GradientDrawable color:${color2} to hexColor:${hexColor}")
                        rtnColor = color2
                    }

                    is ColorDrawable -> {
                        val color = drawable2.color
                        Log.d(tagName, "startBingoAnimation ColorDrawable color:$color")
                        rtnColor = color
                    }

                    else -> {
                        Log.d(tagName, "startBingoAnimation Drawable else")
                    }
                }
            }
        }

        val startColor = Color.parseColor("#FFCC33")
        val endColor = if(rtnColor==0) Color.parseColor("#FF9933") else rtnColor


        val animator = ValueAnimator.ofArgb(startColor, endColor)
        animator.duration = 1000
        animator.addUpdateListener { valueAnimator ->
            val animatedValue = valueAnimator.animatedValue as Int
            bt.setBackgroundColor(animatedValue)
        }
        animator.start()

[안드로이드] 버튼 클릭시 이벤트동작할 때 레이아웃 깨지는 문제


버튼을 클릭할 때마다 이벤트로 버튼 글자 사이즈를 변경하는 이벤트를 넣었는데 위와같이 레이아웃이 깨지는 문제가 발생함

뭐가 문제인지 한참을 헤매다가 결국 해결했다.
아래의 링크에서 나와 똑같은 문제가 있었고 해결방법은 버튼에 layout_gravity=”center_vertical”을 주면 해결된다!!

http://www.masterqna.com/android/35066/%EB%B2%84%ED%8A%BC-text-%EA%B0%9C%ED%96%89%EC%8B%9C-%EB%A0%88%EC%9D%B4%EC%95%84%EC%9B%83-%EA%B9%A8%EC%A7%90