본문 바로가기

프로그래밍/Android

버튼 상태에 따른 배경변경

이미지 버튼을 생성해 보면 흔히 생각하는 형태의 버튼이 아님을 알게되는데

얼마 걸리지 않는다... -_-;; 뭥미~ 라는 1초간의 생각이 지나가고..

 

원래의 목적대로 버튼 상태에 따라 변화하는 이미지 버튼을 고려케 되는데...

방식이야 다양하다.

우선 Button 을 상속받아 각 주요 메쏘드를 오버라이딩 하는 방식이 있는데, 요건

다음에 포스팅할 TextButton과 거의 같은 방법이다.

 

둘째는 selector 를 사용하는 방법으로.. 보다 간편하게 원하는 통작을 이끌어낼 수 있다.

각 상태별로 조건을 두어 이미지를 정의할 수 있는데,

android:state_focused

android:state_pressed

android:state_enabled

등의 조건이 있을 수 있다.

 

res/drawable 폴더에 버튼 배경에 대한 xml 파일을 생성한다.

ex) mybutton_bg.xml

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

   <item android:state_focused="true" android:state_pressed="false" 

   android:drawable="@drawable/button_focus" /> 

   <item android:state_focused="true" android:state_pressed="true" 

   android:drawable="@drawable/button_pressed" /> 

   <item android:state_focused="false" android:state_pressed="true" 

   android:drawable="@drawable/button_pressed" /> 

  <item android:drawable="@drawable/button_normal" />

</selector>

 

저장하고, 위 설정을 지정하고자 하는 버튼의 배경이나 소스로 설정하면된다.

Button은 배경에 지정하고, 이미지 버튼의 경우 src에 지정 후 배경을 투명하게 한다.

배경을 투명으로 하는 것은 ImageButton의 경우 기본 버튼 모양이 생성되기 때문.

<ImageButton

.

.

android:src="@drawable/mybutton_bg"

android:background="#00000000"

.

.

/>

 

혹은 소스상에서 위 리소스를 지정해도 된당.

        ImageButton btn = (ImageButton)this.findViewById(R.id.button1);

        btn.setBackgroundResource(R.drawable.mybutton_bg);

'프로그래밍 > Android' 카테고리의 다른 글

ViewFlipper로 뷰 교체하기  (0) 2009.12.06
에니메이션 interpolater  (0) 2009.12.06
커스텀속성과 R.styleable  (0) 2009.11.25
Splash window 보이기  (0) 2009.11.24
TextButton 만들기  (0) 2009.11.22
에니메이션 처리하기  (0) 2009.11.19
투명한 레이아웃 만들기  (0) 2009.11.18
메시지 핸들러 사용하기  (0) 2009.11.16
리시버를 통한 sms데이터 가져오기  (0) 2009.11.16
Broadcast/BroadcastReceiver  (0) 2009.11.11