2014-11-03 93 views
0

我的问题是,当单个复选框被选中时,它显示它应该的文本。 但是,当两个复选框都被选中时,它只显示第二个文本。字符串返回数字而不是文本?

public class MainActivity extends Activity { 

    TextView text; 
    CheckBox firstCheck, secondCheck; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     firstCheck = (CheckBox) findViewById(R.id.checkBox1); 
     secondCheck = (CheckBox) findViewById(R.id.checkBox2); 
     text = (TextView) findViewById(R.id.textView2); 
    } 

    public void buttonClick(View view) { 
     if(firstCheck.isChecked()) { 
      text.setText(R.string.checkbox_1); 
     } 
     if(secondCheck.isChecked()) { 
      text.setText(R.string.checkbox_2); 
     } 
     if(firstCheck.isChecked()==false && secondCheck.isChecked()==false) { 
      text.setText(R.string.unchecked); 
     } 
    } 
} 

的strings.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <string name="app_name">Les 2_1</string> 
    <string name="hello_world">Hello world!</string> 
    <string name="checkbox_1">Checkbox 1 </string> 
    <string name="checkbox_2">Checkbox 2</string> 
    <string name="button_1">Click here!</string> 
    <string name="textview_2">And?</string> 
    <string name="unchecked">No buttons checked!</string> 

</resources> 
+0

很好地解决这个它去,你当它通过'secondCheck' – tyczj 2014-11-03 16:40:38

+2

还覆盖文本firstCheck.isChecked()== false是多余的,使用!firstCheck.isChecked() – reactivemobile 2014-11-03 16:41:56

回答

0
if(firstCheck.isChecked()) { 
    text.setText(R.string.checkbox_1); 
} 
if(secondCheck.isChecked()) { 
    text.setText(R.string.checkbox_2); 
} 

如果输入了if,则第二个setText将覆盖第一个文本。

您可以通过添加文本

Resources res = getResources(); 
text.setText(text.getText().toString() + res.getString(R.string.checkbox_x)); 

或添加,如果覆盖,当然既

if (firstCheck.isChecked() && secondCheck.isChecked()) { 
    text.setText(res.getString(R.string.checkbox_1) + res.getString(R.string.checkbox_2)); 
} 
+0

text.setText(R.string.checkbox1 + R.string.checkbox2);将无法工作,因为R.string.checkbox1和2正在返回int值!所以,你正在访问错误的资源(如果存在)! – 2014-11-03 16:49:09

+0

@haywire我只是专注于问题的问题..不能检查一切;-) – 2014-11-03 16:51:39

+0

没关系,但请更正它,因为它不会工作。 – 2014-11-03 16:52:18

1

您的代码

if(secondCheck.isChecked()) { 
      text.setText(R.string.checkbox_2); 
     } 

是覆盖文本,所以你需要将checkbox_2文本追加,不仅设置。

+0

Ofcourse,谢谢!相当新的 – Hees1989 2014-11-03 16:42:00

相关问题