2012-11-02 169 views
1

我已經創建了一個應用程序,假設每次點擊都切換按鈕背景顏色。這裏是代碼:切換按鈕背景不起作用

package com.example.flash.light; 

import android.os.Bundle; 
import android.app.Activity; 
import android.graphics.drawable.Drawable; 
import android.view.View; 
import android.widget.Button; 


public class MainActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Button screen = (Button) findViewById(R.id.screen); 
     Drawable background = getResources().getDrawable(R.drawable.black); 
     screen.setBackgroundDrawable(background); 

     screen.setOnClickListener(new Button.OnClickListener(){ 
      public void onClick(View v) { 
       Button screen = (Button) findViewById (R.id.screen); 
       Drawable background = screen.getResources().getDrawable(screen.getId()); 
       if(background == getResources().getDrawable(R.drawable.black)){ 
        Drawable newBackgroun = getResources().getDrawable(R.drawable.white); 
        screen.setBackgroundDrawable(background); 
       } 
       if(background == getResources().getDrawable(R.drawable.white)){ 
        Drawable newBackgroun = getResources().getDrawable(R.drawable.black); 
        screen.setBackgroundDrawable(background); 
       } 
      } 
     }); 
    } 

點擊該按鈕不響應。 感謝

回答

1

試試這個:

public class MainActivity extends Activity { 

    private boolean isBlack = false; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 

     // your code 

     final Button screen = (Button) findViewById (R.id.screen); 
     isBlack = true; 
     screen.setBackgroundColor(Color.BLACK); 
     screen.setOnClickListener(new Button.OnClickListener(){ 
      public void onClick(View v) { 
       if (isBlack){ 
        screen.setBackgroundColor(Color.WHITE); 
        isBlack = false; 
       } 
       else{ 
        screen.setBackgroundColor(Color.BLACK); 
        isBlack = true; 
       } 
      } 

     }); 
} 
} 
2

我相信這裏的問題是資源由您

getResources().getDrawable(int id) 

返回不同的是,每次你怎麼稱呼它。 Android只是構造可繪製類的新實例,而不是返回舊實例。 (至少我相信這種情況下沒有緩存)

使用==運算符比較三個不同的實例永遠不會返回true。

第二件事是在代碼中明顯的bug:

  Button screen = (Button) findViewById (R.id.screen); 
      Drawable background = screen.getResources().getDrawable(screen.getId()); 
      if(background == getResources().getDrawable(R.drawable.black)){ 
       Drawable newBackgroun = getResources().getDrawable(R.drawable.white); 
       screen.setBackgroundDrawable(**newBackground**); 
      } 
      if(background == getResources().getDrawable(R.drawable.white)){ 
       Drawable newBackgroun = getResources().getDrawable(R.drawable.black); 
       screen.setBackgroundDrawable(**newBackground**); 
      } 

,而不是背景你應該有newBackground那裏。

+1

所以如何解決? – vlio20

+0

@VladIoffe更新回答 - 粘貼的固定代碼被剪掉。但它仍然不能解決我相信不同實例的問題。但你可以先嚐試一下。 –