2011-11-11 105 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