2013-03-02 120 views
1

您好再次我有另外一個問題,關於我的Hello World程序 我希望當按下按鈕,我這樣做是爲了改變背景:Android應用背景顏色按鈕

public void onclick01(View View) 
     { 
      View.setBackgroundColor(Color.GREEN); 

     } 

但改變的背景顏色該按鈕,而不是整個應用程序。


編輯

我有兩個問題。

1)我將如何設置

View.setBackgroundColor(Color.GREEN); 

喜歡的東西:

View.setBackgroundColor(Color.RANDOM); 

2)我怎麼會做同樣的改變文字顏色? 類似:

View.setTextColor(Color.GREEN);? 

回答

1

main_act.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/layout" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <Button 
     android:id="@+id/b1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="button" /> 

</LinearLayout> 

活動

public class MainActivity extends Activity { 
/** Called when the activity is first created. */ 
Button b1; 
LinearLayout layout; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main_act); 
    layout=(LinearLayout)findViewById(R.id.layout); 
    blueButton=(Button)findViewById(R.id.b1); 
    b1.setOnClickListener(new OnClickListener() { 

     public void onClick(View arg0) { 
     // TODO Auto-generated method stub 
     layout.setBackgroundColor(Color.BLUE); 

    } 
}); 
} 
} 
0

如果你想通過XML設置,那麼你需要如下操作:

android:background="@android:color/green" 

的情況下,如果你決定使用Android的默認顏色代碼,或者如果你有顏色在colors.xml指定,則使用

android:background="@colors/green" 

如果你想以編程方式做,然後做:

 LinearLayout linearlayout=(LinearLayout) findViewById(R.layout.yourlayout); 
    linearlayout.setBackgroundColor(Color.GREEN); 
+0

我該怎麼把爲(R.layout 「YourLayout」。) – Cnorwood7641 2013-03-03 18:52:51

+0

ID佈局的....機器人:ID = 「@ + ID/yourlayout」 ???? – Shiv 2013-03-04 04:35:37

0

這裏查看引用你的按鈕的視圖。所以,你需要爲其父佈局創建對象的再

layout.setBackgroundColor(Color.GREEN); 
0
public void setActivityBackgroundColor(int color) { 
view = this.getWindow().getDecorView(); 
view.setBackgroundColor(color); 
} 

然後從你的OnClickListener通過調用它在任何c olor你想要的。

+0

這段代碼給了我幾個錯誤信息。 – Cnorwood7641 2013-03-03 18:50:32

0

你應該使用XML對於這種情況

<selector xmlns:android="http://schemas.android.com/apk/res/android" > 

<item android:state_pressed="true"> 
    <shape android:shape="rectangle"> 
     <solid android:color="yourColor"/> 
    </shape> 
</item> 

<item> 
    <shape android:shape="rectangle"> 
     <solid android:color="yourColor"/> 
    </shape> 
</item> 

</selector> 
0

使用Selector你會得到按鈕按壓動作。

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:drawable="@drawable/button_background" android:state_pressed="false"/> 
<!-- default --> 
<item android:drawable="@drawable/button_pressed" android:state_pressed="true"/> 
<!-- pressed --> 
</selector>