我在确定是否选中了复选框时遇到问题。这是因为它们是动态生成的。我尝试为每个动态复选框创建OnCheckedChangeListener(),但确定只有最后一个动态复选框的OnCheckedChangeListener()被执行。
这是我的代码片段(希望它会有所帮助):
public class yc_SubmitAttendance_ClassMode extends Activity {
Context myContext = this;
myDbAdapter myDB = null;
Cursor myCur = null;
Spinner mySpin = null;
TableLayout tl = null;
CheckBox myCB = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yc_studattend_classmode_layout);
mySpin = (Spinner)findViewById(R.id.spinClassModeSelectModGrp);
myDB = new myDbAdapter(myContext);
tl = (TableLayout)findViewById(R.id.classModeTableLayout);
//retrieve dynamic data
myCur = myDB.retrieveAttnForSelectedMod(mySpin.getItemAtPosition(arg2).toString());
myCur.moveToFirst();
for(byte rowNo=0;rowNo<myCur.getCount();rowNo++)
{
TableRow tr = new TableRow(myContext);
/*Some codes intentionally left missing */
myCB = new CheckBox(myContext);
myCB.setId(rowNo);
//Setting a onCheckedListener on each of the checkbox generated
myCB.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0,
boolean arg1) {
// TODO Auto-generated method stub
myCur.moveToPosition(myCB.getId());
if(myCB.isChecked())
{
Toast.makeText(myContext,"Attendance deducted to " + ((myCur.getFloat(2)) - 2) + "%", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(myContext,"Attendance reverting to " + (myCur.getFloat(2)) + "%", Toast.LENGTH_SHORT).show();
}
}
});
//Insert the checkbox onto this row
tr.addView(myCB);
//Append this row to the TableLayout
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
myCur.moveToNext();
} //end of for-loop
} // end of onCreate
}//end of class
但是,我想要的是能够确定每个动态复选框是否已选中或未选中。
Yeong Chai
答案 0 :(得分:0)
将此代码替换为:
myCB.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton thisCheckBox,
boolean isChecked) {
// TODO Auto-generated method stub
myCur.moveToPosition(thisCheckBox.getId());
if(isChecked)
{
Toast.makeText(myContext,"Attendance deducted to " + ((myCur.getFloat(2)) - 2) + "%", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(myContext,"Attendance reverting to " + (myCur.getFloat(2)) + "%", Toast.LENGTH_SHORT).show();
}
}
问题是你使用myCB.isChecked()而不是第二个参数“arg1”来确定CheckBox是否被选中。 myCB将始终指向您创建的最后一个CheckBox,因为每次循环时都会分配它。