2013-05-19 26 views
28

Tôi đã một file xml drawable (background.xml):Thay đổi hình dạng màu rắn tại thời gian chạy bên trong xml drawable sử dụng làm nền

<?xml version="1.0" encoding="UTF-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > 
    <item> 
     <shape> 
     ........... 
     </shape> 
    </item> 

    <item android:id="@+id/shape_id"> 
     <shape android:shape="rectangle"> 
      <solid android:color="#ffefefef" /> 
     </shape> 
    </item> 

</layer-list> 

sử dụng bởi một LinearLayout:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:background="@drawable/background" 
    android:id="@+id/layout_id" 
    > 

Bây giờ tôi cần để thay đổi hình dạng màu shape_id ở thời gian chạy dựa trên một số điều kiện. làm như thế nào?

+0

không tôi không nghĩ là có thể – Raghunandan

+7

Impossible is nothing – AndroidGecko

Trả lời

59

Tìm thấy bởi tôi:

View v = findViewById(R.id.layout_id); 

    LayerDrawable bgDrawable = (LayerDrawable)v.getBackground(); 
    final GradientDrawable shape = (GradientDrawable) bgDrawable.findDrawableByLayerId(R.id.shape_id); 
    shape.setColor(----); 
+3

Bạn có bất cứ ý tưởng làm thế nào để thực hiện giống nhau trên RemoteView cho widget? Cảm ơn. – rxlky

+0

Xin lỗi, nhưng tôi chưa có cơ hội làm việc với RemoteView .. –

+0

@ MV1 Điều này có thể ở chế độ xem từ xa. Bởi vì nó không hoạt động. Bạn có thể hướng dẫn tôi http://stackoverflow.com/questions/24545857/how-to-change-remote-view-background-in-runtime?noredirect=1#comment38013228_24545857 –

Các vấn đề liên quan