2012-05-04 108 views
0

應用程序運行時是否可以在Java代碼中更改矩形(用xml繪製)顏色?在應用程序運行時更改XML形狀顏色

我rectangle.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape"> 
    <stroke android:width="2dp" android:color="#ffffff" /> 
    <padding android:left="20dp" 
     android:top="20dp" 
     android:right="20dp" 
     android:bottom="20dp" /> 

    <solid android:color="#006600" /> 
</shape> 

通過繪製main.xml中:

<View 
    android:id="@+id/myRectangleView" 
    android:layout_width="wrap_content" 
    android:layout_height="100dp" 
    android:background="@drawable/rectangle"/> 

我已經試過這樣:

GradientDrawable sd; 
    View viewrectangle; 
    viewrectangle = (View) findViewById(R.id.myRectangleView); 
    sd = (GradientDrawable) viewrectangle.getBackground(); 
    sd.setColor(0xffffff00); 
    sd.invalidateSelf(); 

它只有當我把作品它在OnCreate方法中。

我想通過按鈕來改變矩形的顏色,所以我把這個代碼放在按鈕的onClick()方法中。但是當我點擊按鈕時,應用程序運行顏色不會改變。有什麼建議麼?

+1

如果以下任何答案都可以解決您的問題,或者幫助您解決問題,您應該點擊該答案旁邊的複選標記以將其標記爲已接受的答案並賦予作者信用評分。 – Barak

回答

0

你可以把這個代碼在一個單獨的方法,並且該方法可以從按鍵的的onClick調用..

2

使用這個代碼和它的工作,或者考慮使用重繪viewrectangle.invalidate()的viewrectangle,但它不應該是nescarry:

View viewrectangle; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    viewrectangle = (View) findViewById(R.id.myRectangleView); 

} 

public void doClick(View v) { 
    GradientDrawable sd = (GradientDrawable) viewrectangle.getBackground(); 
    sd.setColor(0xffffff00); 
    sd.invalidateSelf(); 
} 

在這個例子中, 「doClick()」 方法在main.xml中設置:

<Button android:layout_height="wrap_content" 
     android:layout_width="match_parent" 
     android:text="Button" 
     android:onClick="doClick"/> 
0

你可以嘗試結腸r過濾器。我之前使用它來改變按鈕的顏色(請注意,它們以標準灰色開始),如果從另一種顏色開始,它可能會是一個非常不同的結果。反正我是如何做的一個例子:

導入PorterDuff圖形的東西:

import android.graphics.PorterDuff; 

在類中定義爲彩色濾光片所需的項目,並設置過濾器:

Button atdButton = (Button) convertView.findViewById(R.id.attendbutton); 

    if (atdState[position].equals("P")) { 
     atdButton.getBackground().setColorFilter(0xFF00FF00, // Set filter to green 
       PorterDuff.Mode.MULTIPLY); 
    } else if (atdState[position].equals("T")) { 
     atdButton.getBackground().setColorFilter(0xFFFFFF00, // Set filter to yellow 
       PorterDuff.Mode.MULTIPLY); 
    } else if (atdState[position].equals("E")) { 
     atdButton.getBackground().setColorFilter(0xFFFF6600, // Set filter to orange 
       PorterDuff.Mode.MULTIPLY); 
    } else if (atdState[position].equals("U")) { 
     atdButton.getBackground().setColorFilter(0xFFFF0000, // Set filter to red 
       PorterDuff.Mode.MULTIPLY); 
    } else { 
     atdButton.getBackground().clearColorFilter(); 
    }