我的活动有一个带有两个单选按钮和保存按钮的 RadioGroup,它将一个值保存在字符串变量“类型”中。第一个单选按钮将类型初始化为“禁食”,第二个按钮将“类型”初始化为“非禁食”。如果我选择第二个选项,则类型不会被初始化。要使第二个按钮起作用,我必须选择第一个按钮并单击保存,然后如果我再次选择第二个选项,那么它将起作用。这是代码。
糖尿病选项.xml
<RadioGroup
android:id="@+id/do_radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/do_editText1"
android:visibility="visible" >
<RadioButton
android:id="@+id/do_fasting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fasting" />
<RadioButton
android:id="@+id/do_nonfasting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Non Fasting" />
</RadioGroup>
DiabetesOptions.java(保存按钮的 onClick 方法内)
public class DiabetesOptions extends Activity {
int typeFlag=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
rGroup=(RadioGroup)findViewById(R.id.do_radioGroup1);
}
//This is the method invoked if we click Sabe button
public void onSave(View view) {
rGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch(checkedId){
case R.id.do_fasting:
type="Fasting";
typeFlag=1;
break;
case R.id.do_nonfasting:
type="Non Fasting";
typeFlag=1;
break;
}
}
});
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
date = dateFormat.format(new Date());
time = timeFormat.format(new Date());
try {
if(flag==1) {
DiabetesDatabase entry = new DiabetesDatabase(this);
if(typeFlag==1){
entry.createEntry(date,time,type,level);
Toast th = Toast.makeText(DiabetesOptions.this, "Entry Saved", Toast.LENGTH_SHORT);
th.show();
}
else if(typeFlag==0){
AlertDialog.Builder alertDialog=new AlertDialog.Builder(DiabetesOptions.this);
alertDialog.setTitle("Alert!!!");
alertDialog.setMessage("Select FASTING or NON FASTING option");
alertDialog.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}