본문 바로가기
개발/android

버튼의 Selector 이미지를 간절히 가져오고 싶다면?

by 매몰 2016. 3. 28.

 

 

보통 Selector를 xml로 아래와 같이 만들어 놓는다.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false" android:drawable="@drawable/btn" />
    <item android:state_pressed="true" android:drawable="@drawable/btn_press" />
</selector>

 

 

그리고 버튼 background에 적용한다.

<Button android:id="@+id/Button" android:text="@string/btn"
android:layout_width="

100dp

" android:layout_height="

100p

"

android:background="@drawable/btn_selector"/>

 

 

 

별로~ 그럴일은 없지만 만약 이 selector의 android:drawable 이미지를 자바 코드상으로 불려오고 싶다면??

 

private Drawable[] getPressImages(View v) {
    //Selector 이미지를 StateListDrawable 객체로 불러옴
    StateListDrawable statedrawable = (StateListDrawable)v.getBackground();
    if(statedrawable != null) {
        try {
            //Veiw의 현재 이미지 상태를 배열에 가져옴
            int[] currentstate = v.getDrawableState();

            //이미지를 불러오기 위해 인덱스와 이미지 메소드를 가져옴
            Method indexmethod = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class);
            Method drawblemethod = StateListDrawable.class.getMethod("getStateDrawable", int.class);

            //인덱스 메소드와 상태 배열을 이용해 StateListDrawable의 리스트 인덱스를 가져옴
            int index = (int) indexmethod.invoke(statedrawable, currentstate);

            //얻어낸 리스트 인덱스로 StateListDrawable에서 이미지를 각각 불러옴 
            Drawable drawable1 = (Drawable) drawblemethod.invoke(statedrawable, index);
            Drawable drawable2 = (Drawable) drawblemethod.invoke(statedrawable, index + 1);

            return new Drawable[] {drawable1, drawable2};

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    return null;
}

 

 

 

 

 

 

 

도움이 되셨다면~ 정성으로 빚은 저희 앱!  많은 이용 바래요:)

 

https://meorimal.com/index.html?tab=spaceship

 

우주선 - 방치형 인공지능 투자 체험기

미리 맛보는 인공지능 투자!

(주)머리말 meorimal.com

 

https://meorimal.com/subway.html

 

지하철어디있니

더이상 고민하지 마세요. 뛸지 말지 딱 보면 알죠.

(주)머리말 meorimal.com

 

사업자 정보 표시
주식회사 머리말 | 고영진 | 서울특별시 송파구 중대로 135 서관 10층 (가락동, 아이티벤처타워) | 사업자 등록번호 : 524-88-00727 | TEL : 010-9990-3674 | Mail : gyjmeba@hanmail.net | 통신판매신고번호 : 2017-서울강남-03941호 | 사이버몰의 이용약관 바로가기