2012-01-14 91 views
0

我在確定複選框是否被選中時遇到問題。這是因爲它們是動態生成的。我試圖爲每個動態複選框創建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 

但是,我想要的是能夠確定每個動態複選框是否已選中或未被選中。

永柴

回答

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」,以確定是否複選框被選中或不。 myCB將始終指向您創建的最後一個CheckBox,因爲每次循環時都會分配它。

+0

Hii Grazahd,謝謝你的快速回復。它現在像一個冠軍,它澄清了我對** onCheckedChangeListener()**的理解。一個值得讚賞的大拇指。 – 2012-01-16 12:01:35

相關問題