获取复选框以输出,如果选中则为yes,如果未选中则为no

时间:2018-10-06 16:48:38

标签: android checkbox

我有一个复选框。我需要它以在textView中查看结果。如果选中,它需要说是,如果未选中,它需要说是。如果能够选中/未选中,我能够使它显示为false,但是我需要说是/否。复选框文本询问是或否的问题。我必须使用共享首选项。这就是我所拥有的,它返回的是非。

public void addStudent(View view){
   Boolean major;
   if(Major.isChecked())
   {
       major = true;
   }
   else
   {
       major = false;
   } 

   SharedPreferences sharedPreferences = 
   getSharedPreferences("StudentInfo", Context.MODE_PRIVATE);
   SharedPreferences.Editor editor = sharedPreferences.edit();


   editor.putString("memberFirstName", firstName.getText().toString());
   editor.putString("memberLastName", lastName.getText().toString());
   editor.putInt("sId", studentId);
   editor.putBoolean("major", major);
   editor.commit();
   firstName.setText("");
   lastName.setText("");

   Toast.makeText(this, "Student Added!", Toast.LENGTH_SHORT).show();
   }
   public void viewMembers(View view)
   {

   SharedPreferences sharedPreferences = 
   getSharedPreferences("StudentInfo", Context.MODE_PRIVATE);

   String first = sharedPreferences.getString("memberFirstName", "");
   String last = sharedPreferences.getString("memberLastName", "");
   int id = sharedPreferences.getInt("sId", 0);
   Boolean MajorCis = sharedPreferences.getBoolean("major", true);

  viewStudents.setText("Student Name:"+ " " +first + " " + last + "\n" 
   + "Student Id: " + id + "\n" +"CIS Major: " + MajorCis);

2 个答案:

答案 0 :(得分:0)

只需根据复选框状态设置文本"Yes/No"

textView.setText(checkbox.isChecked()?"Yes":"No");

答案 1 :(得分:0)

请使用此示例代码

CheckBox checkbox=(CheckBox)findViewById(R.id.checkbox);
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    textview.setText("YES");
                }else{
                    textview.setText("NO");
                }
            }
        });