2011-11-11 107 views
0

我在notepadv3教程中實現了radiobuttongroup。 如果字符串輸出是「Fehltag」或「Verspaetung」,我想設置一個單選按鈕。 它不是完整的源代碼。單選按鈕設置檢查如果

<RadioGroup 
    android:id="@+id/radioGroup1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" > 

    <RadioButton 
     android:id="@+id/rbtnVerspaetung" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/rbtnVerspätung" /> 

    <RadioButton 
     android:id="@+id/rbtnFehltag" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/rbtnFehltag" /> 
</RadioGroup> 

的java:

private RadioButton rbtnFehltag; 
    private RadioButton rbtnVerspaetung; 
    private void populateFields() { 

    if (mRowId != null) { 
     Cursor note = mDbHelper.fetchNote(mRowId); 
     startManagingCursor(note); 
     mTitleText.setText(note.getString(
       note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE))); 
     mBodyText.setText(note.getString(
       note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY))); 
     mFehlzeitText.setText(note.getString(
       note.getColumnIndexOrThrow(NotesDbAdapter.KEY_Time))); 
     mTest.setText(note.getString(
       note.getColumnIndexOrThrow(NotesDbAdapter.KEY_Test))); 

     String ausgabe; 
     //returns Verspaetung or Fehltag 
     ausgabe = note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_Test)); 

     rbtnFehltag.setChecked(ausgabe == "Verspaetung"); //it doesn't work 
     //rbtnFehltag.setChecked(true); //this is working but it doesn't peform the task 

    } 

回答

1

我不知道我理解你的要求。但我認爲你的問題在於你不能在字符串上使用==運算符。我相信==運算符會比較內存中的字符串位置,而不是字符串的內容。我想如果你用這個替換代碼的尾部:

String ausgabe; 
//returns Fehltag  or  Verspaetung 
ausgabe = note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_Test)); 
rbtnFehltag = (RadioButton)findViewById(R.id.rbtnFehltag); 
rbtnVerspaetung = (RadioButton)findViewById(R.id.rbtnVerspaetung); 
rbtnFehltag.setChecked(ausgabe.equals("Fehltag")); 
rbtnVerspaetung.setChecked(ausgabe.equals("Verspaetung")); 

字符串實際上是Java中的對象。一般來說,在比較原語時只應使用==運算符。 ==會比較對象的內存地址。當你需要了解身份而不是平等時,這很有用。但我不認爲這就是你要去的地方。

祝你好運。

+0

我是java的新手...我認爲在C#中,你可以讓它如此(字符串==「abc」)...感謝您的快速回答 – Ertan

+0

沒有問題。我記得當我學習Java時,花費了幾個小時來處理==運算符和Strings。只要記住,你有兩個選項等於等於和點等於。對基元使用equals-equals並用於測試與對象的身份。在測試與對象的相等性時使用dot-equals。這幾乎總是意味着你必須實現'public boolean equals(Object obj)''通過這種方式,您可以準確定義與您一起工作的任何對象的「平等」。當然,字符串是一個特殊的情況,其中dot-equals已經以正確的方式實現。 – b3bop

+0

請注意,所有對象最終都將從Object類繼承。我相信Object實現.equals。但我認爲它比較默認情況下的內存地址,這幾乎肯定不是你想要的。 – b3bop