簡體   English   中英

如果XML中定義了顏色,則無法更改視圖的背景色

[英]Can't change background color of the View if color defined in the XML

我遇到了一個奇怪的問題。 我有一個RelativeLayout,我通過以下方式在XML中定義背景色:

 <RelativeLayout ..
      android:background="#449966">
 </RelativeLayout>

現在,我想以編程方式更新背景色,所以我這樣做了:

 view.setBackgroundColor( Color.argb( 255, 200, 150, 133 ) );

僅當我從XML文件中刪除background屬性時,這才奇怪。 如果存在background屬性,則以編程方式設置時背景顏色不會更改。

因此,由於background屬性似乎期望使用Drawable ,所以我想也許我也需要創建一個drawable並使用setBackground方法,所以我這樣做了:

 Drawable newColor = new ColorDrawable( Color.argb( 255, 200, 150, 133 ) );
 view.setBackground( newColor );

但是,如果XML中存在background屬性,則背景顏色仍然不會改變。 似乎如果在XML中定義了background屬性,則不能對其進行“ 覆蓋 ”。

有什么建議嗎? 謝謝!

這是因為每個視圖的行為都與其他視圖不同,並且當您嘗試更改常規視圖的顏色(即“布局”視圖)時將永遠無法使用,因此應通過id調用“ RelativeLayout”,然后更改其視圖:

 <RelativeLayout
  android:id="@+id/myview"
  android:background="#449966">
 </RelativeLayout>

在java中:

 view.findViewById(R.id.myview).setBackgroundColor(Color.argb( 255, 200, 150, 133 ));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM