2012-03-16 83 views
0

我有一個選項Activity,其中我使用RadioButton選擇顏色。默認情況下,White顏色設置爲android:checked="true"。現在,當我到達我的Canvas時,我需要動態更改Paint顏色,具體取決於哪個RadioButton被選中。 下面是我曾嘗試代碼:在Android中動態更改繪畫對象的顏色

  String radioButtonSelected = ""; 
      switch (checkedRadioButton) { 
       case R.id.CheckRed : radioButtonSelected = "Red"; 
               break; 
       case R.id.CheckBlue : radioButtonSelected = "Blue"; 
              break; 
       case R.id.CheckWhite : radioButtonSelected = "White"; 
              break; 
      } 
      Intent i = new Intent(HandwritingRecognitionOptionTab.this,HandwritingRecognitionCanvas.class); 
      i.putExtra("setColor",radioButtonSelected); 
      //startActivity(i); // because I don't want to start the activity immediately after this 

在類Canvas

 Bundle getValue = getIntent().getExtras(); 
     drawColor = getValue.getString("setColor"); 
     if(drawColor.equals("White")) 
      intColor = 1; 
     if(drawColor.equals("Red")) 
      intColor = 2; 
     if(drawColor.equals("Blue")) 
      intColor = 3; 


     mPaint = new Paint(); 
     mPaint.setDither(true); 
     mPaint.setColor(Color.WHITE); 
     if(intColor == 1) 
      mPaint.setColor(Color.WHITE); 
     if(intColor == 2) 
      mPaint.setColor(Color.RED); 
     if(intColor == 3) 
      mPaint.setColor(Color.BLUE); 

,但我得到每當ActivityCanvas啓動一個NullPointerException。重要的是要注意,默認情況下,白色應該是顏色。另外,這不會永久保存它嗎?我應該看看SharedPreferences嗎?

+0

如果這不是你開始第二個活動的地方,那麼你可以把無論你是否開始第二個活動的相關代碼。 – Deva 2012-03-16 09:36:09

+0

我不從此活動開始其他活動。我感覺我在這種方法中完全錯誤,即選擇putExtra()。 – 2012-03-16 09:38:36

回答

1

在閱讀完您的評論之後,它看起來像是您沒有使用給定的Intent啓動其他活動,因此NullPointerException作爲Bundle將不會在下一個活動中包含相同的字符串。

您可以選擇退出以下選項:

1> Shared Prefrences (As highlighted by you) 
2> Some DB entry. 
3> Some file storage 
4> Singleton pattern 

,但對我最好的人會是一個共享prefrence。你也許還想看看這個link的詳細信息