2014-01-30 3 views
4

res/drawable/my_background.xml에 drawable이 정의되어 있습니다.xml StateListDrawable을 Java에서 수정하십시오.

my_background.xml은 다음과 같습니다

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_pressed="true"> 
     <layer-list > 
      <item android:drawable="@drawable/product_background_1" /> 
      <item> 
       <rotate 
        android:fromDegrees="180" 
        android:toDegrees="180" 
        android:pivotX="50%" 
        android:pivotY="50%" 
        android:drawable="@drawable/product_background_2" 
        android:id="@+id/need_to_change_this_color_from_java" /> 
      </item> 
      <item><color android:color="#4400aa00"/></item> 
     </layer-list> 
    </item> 
    <item> 
     <layer-list > 
      <item android:drawable="@drawable/product_background_1" /> 
      <item android:drawable="@drawable/product_background_2" /> 
     </layer-list> 
    </item> 
</selector> 

나는 다음 뷰 당김으로 my_background 설정하고 잘 작동합니다.

하지만 내 선택기의 layerList에 저장된 자바 요소의 값을 자바 코드에서 변경해야합니다. 어떻게해야합니까?

내 뷰에서 getBackground()를 호출 한 다음 StateListDrawable을 가져올 수 있지만 StateListDrawable에서 드로어 블 자식을 가져 오는 메서드를 찾을 수 없습니다.

답변

11

...하지만 drawable 자식을 가져 오는 방법은 찾을 수 없습니다. StateListDrawable.

DrawableContainerState 수퍼 클래스 인 클래스 DrawableContainer을 통해 자녀를 액세스 할 수 있습니다. 이 클래스는 두 개의 LayerDrawable을 포함하는 배열을 반환하는 getChildren() 메서드를 가지고 있습니다. 그런 다음 추가 대상 당김에 도착하는 그 당김을 조작 할 수 있습니다 :

StateListDrawable sld = (StateListDrawable) theView.getBackground(); 
DrawableContainerState dcs = (DrawableContainerState) sld.getConstantState(); 
Drawable[] children = dcs.getChildren(); 
RotateDrawable target = (RotateDrawable) ((LayerDrawable) children[0]).getDrawable(1); // or use the id 
// use target to change the color 

가 직접 적절한 LayerDrawable를 검색 할 수 있도록 DrawableContainerStategetChild() 방법을 노출 킷캣 (API 레벨 19)을 시작으로.

+0

감사합니다. 완벽하게 작동합니다. – MTilsted

0

R.java은 그 안에있는 모든 xml의 인스턴스 (정적)를 저장하는 파일이므로이 작업을 수행 할 수 있다고 생각하지 않습니다. 정적이란 손에 들어가기 전에 메모리에 머물러 있어야한다는 것을 의미합니다. 가능성이있다.

관련 문제