2012-11-08 49 views
0

在我的程序中,當用戶按下按鈕時,我想根據已經存在的內容將文本設置爲其他內容,但它不起作用。 當我單擊按鈕時,沒有任何反應,文本保持不變 這是製作按鈕的xml佈局。他們調用函數NEXTVAL如何從另一個按鈕上設置文本android

<Button 
       android:id="@+idk/kbutton1" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_weight="1" 
       android:onClick="nextVal" 
       android:text="@string/zero" /> 

      <Button 
       android:id="@+idk/kbutton3" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_weight="1" 
       android:onClick="nextVal" 
       android:text="@string/x" /> 

      <Button 
       android:id="@+idk/kbutton4" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_weight="1" 
       android:onClick="nextVal" 
       android:text="@string/one" /> 

被稱爲

public void nextVal(View view) 
    { 

     Button b = (Button) findViewById(view.getId()); 
     System.out.println(b.getText().toString()); 

     switch(view.getId()) 
     { 
     case R.idk.kbutton4: 
      if(b.getText().toString() == "0") 
       b.setText("1"); 
      else if(b.getText().toString() == "1") 
       b.setText("x"); 
      else if(b.getText().toString() == "x") 
       b.setText("0"); 
      break; 
     case R.idk.kbutton3: 
      if(b.getText().toString() == "0") 
       b.setText("1"); 
      if(b.getText().toString() == "1") 
       b.setText("x"); 
      if(b.getText().toString() == "x") 
       b.setText("0"); 
      break; 
     case R.idk.kbutton2: 
      if(b.getText().toString() == "0") 
       b.setText("1"); 
      if(b.getText().toString() == "1") 
       b.setText("x"); 
      if(b.getText().toString() == "x") 
       b.setText("0"); 
      break; 
     } 

    } 
+1

發生了什麼事?它有錯誤嗎? – iTurki

+0

嘗試使用b.getText()。toString.equals(「0」) – Delpes

回答

0

您正在使用==操作符來比較兩個字符串的函數。 ==運算符檢查引用是否相同,而不是內容是否相同。相反,你應該使用b.getText.ToString()。equals(「x」);}。

這就是說,我有一些額外的建議。您正在使用findViewById()來查找已被傳遞的視圖。您可以替換findViewById(view.getId()),而只是將視圖轉換爲按鈕。

此外,你可以擺脫switch語句,因爲除了混淆代碼之外它確實對你沒有好處。你無論如何都在做同樣的事情,那麼爲什麼呢?只需將其替換爲其中一種可能性的內容即可。

所以你NEXTVAL()可能看起來像:

public void nextVal(View view) 
    { 
     Button b = (Button) view; 

     if(b.getText().toString().equals("0")){ 
       b.setText("1"); 
     }else if(b.getText().toString().equals("1")){ 
       b.setText("x"); 
     }else if(b.getText().toString().equals("x")){ 
       b.setText("0"); 
     } 
    } 
+0

非常感謝!我原本沒有開關,只是做了你所做的,但它不工作,因爲我使用== – rasen58

+0

但是,你不能說按鈕b =(Button)view();沒有函數叫做view() – rasen58

+0

糟糕。我從OP的代碼複製並粘貼並編輯它,所以一定是意外停留在這裏。謝謝你的提示。固定。 – ajpolt

1

您已經使用@+idk/case R.idk而不是id整個代碼,切換所有這些使view.getId()知道什麼返回。例如:

<Button 
    android:id="@+id/kbutton3" 
    ... /> 

和:

case R.id.kbutton3: 

(我猜view.getId()當前爲每個按鈕返回View.NO_ID

+0

其實它確實返回正確的ID。我通過輸出值 – rasen58

+0

進行了檢查,我對此感到有點驚訝,並且這個編譯...無論你以後使用標準符號和組織來防止意外錯誤,我很高興你有一個工作解決方案。 – Sam

0

的==操作符不比較的字符字符串。使用.equals()代替。

相關問題