0

我有一个onCheckedChanged告诉我 aRadioButton中的 aRadioGroup是否被推。

RadioGroup rGroup = (RadioGroup)findViewById(R.id.rdgroup);
        // This will get the radiobutton in the radiogroup that is checked
        RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(rGroup.getCheckedRadioButtonId());

        rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            public void onCheckedChanged(RadioGroup rGroup, int checkedId)
            {
                // This will get the radiobutton that has changed in its check state
                RadioButton checkedRadioButton = (RadioButton)rGroup.findViewById(checkedId);
                // This puts the value (true/false) into the variable
                boolean isChecked = checkedRadioButton.isChecked();
                // If the radiobutton that has changed in check state is now checked...
                if (isChecked)
                {
                    String tmp = checkedRadioButton.getText().toString();
                    //Toast t = Toast.makeText(NeuesKind.this, checkedRadioButton.getText(), Toast.LENGTH_SHORT);
                    //
                   // t.show();
                    if(tmp == "Männlich"){
                        geschlecht = "männlich";
                    }
                    if(tmp == "Weiblich"){
                        geschlecht = "weiblich";
                    }

                    Toast t1 = Toast.makeText(NeuesKind.this, geschlecht, Toast.LENGTH_SHORT);
                    t1.show();
//                  Toast t = Toast.makeText(NeuesKind.this, checkedRadioButton.getText(), Toast.LENGTH_SHORT);
//                  t.show();
                }
            }
        });

当我使用Toast现在被淘汰的第一个时,它告诉我 tmp 是“Männlich”或“Weiblich”。当我使用第二个Toast t1时,我告诉我geschlecht是空的。geschlecht 的声明在我的课堂上是最重要的,因为我在onCreate课堂上也需要它。

为什么 geschlecht 不采用 tmp 的值?

4

3 回答 3

3

在 Java 中,doing==意味着它将比较两个对象的引用。您需要通过调用 stringequals方法实际比较对象中的文本,如下所示:

                if (tmp.equals("Männlich")) {
                    geschlecht = "männlich";
                }

                if (tmp.equals("Weiblich")) {
                    geschlecht = "weiblich";
                }

但是,您这样做也会容易得多:

geschlecht = tmp.toLowerCase(); // toLowerCase will make all the characters lowercase (as you've done in your if block)
于 2013-05-06T08:52:40.593 回答
1

您不是将 String 内容与您的代码进行比较,而是对象,使用equalsor equalsIgnoreCase,如下所示:

if ("Männlich".equalsIgnoreCase(tmp)) {
    geschlecht = "männlich";
}
if ("Weiblich".equalsIgnoreCase(tmp)) {
    geschlecht = "weiblich";
}
于 2013-05-06T08:54:41.727 回答
1

tmp.compareTo ( "Mannlich" )不使用tmp ==

于 2013-05-06T08:55:11.760 回答