곰돌푸우❤️

Drawable의 mutate함수

2016. 11. 28. 14:56

목차

    안드로이드에서 Drawable은 하나의 Constant State를 공유한다.


    Drawable star = context.getResources().getDrawable(R.drawable.star);
    if (book.isFavorite()) {
      star.setAlpha(255); // opaque
    } else {
      star.setAlpha(70); // translucent
    }

    위와 같이 여러번 Drawable을 생성해도 하나의 Constant State를 공유하기 때문에


    모든 star의 Drawable은 같은 alpha값을 가지게 된다.


    따라서 


    Drawable star = context.getResources().getDrawable(R.drawable.star); if (book.isFavorite()) { star.mutate().setAlpha(255); // opaque } else { star.mutate().setAlpha(70); // translucent }

    와 같이 mutate를 호출 해주어 alpha값을 셋팅해주면 해당 Drawable만 특정 alpha값을 가질 수 있다.


    mutate는 Drawable을 완전 복사 하는 것이 아니라 상수상태만을 복사해서 리턴한다.



    참고로 Drawable의 클래스를 뒤져보면 

    public @NonNull Drawable mutate() {
    return this;
    }

    새로 생성하지 않고 this로 자신을 리턴하고 있다.





    원문

    http://android-developers.blogspot.kr/2009/05/drawable-mutations.html


    해석 

    https://sites.google.com/site/endihom/home/programming-language/android/article/drawable

    facebook twitter googleplus kakaostory naver