我在我的布局中创建了一些checkboxex,我必须根据复选框的状态更新数据库....我怎么能这样做?下面是代码 的 DynamicActivity.java
package com.android.layout;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class DynamicActivity extends Activity {
/** Called when the activity is first created. */
DBAdapter db = new DBAdapter(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
char[] save={'s','a','v','e'};
db.open();
long id;
for(int i=0;i<25;i++){
id = db.insertRow("08241A05"+(i+10),1);
}
Cursor c=db.getAllRows();
startManagingCursor(c);
c.moveToFirst();
ScrollView sv=new ScrollView(this);
TableLayout tl=new TableLayout(this);
for(int i=0;i<25;i++){
TableRow tr=new TableRow(this);
TextView tv= new TextView(this);
tv.setText(c.getString(c.getColumnIndexOrThrow(db.KEY_ROLLNO)));
tv.setPadding(0, 1, 10, 1);
tr.addView(tv);
c.moveToNext();
CheckBox cb=new CheckBox(this);//creation of checkboxes
cb.setChecked(true);
cb.setId(i+10);
tr.addView(cb);
tl.addView(tr);
}
Button saveButton=new Button(this);
saveButton.setText(save,0,4);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
update();
}
});
tl.addView(saveButton);
sv.addView(tl);
setContentView(sv);
}
protected void update() {
//i am trying get the vlaues here and update when save button is pressed
if(cb1.isChecked()){
db.update("", 1);
}
else{db.update("",0);}
db.close();
}
}
我想知道在update方法中检索所有checkboxex状态的最佳方法是什么?
答案 0 :(得分:1)
CheckBox cb=new CheckBox(this);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener{
@Override
public void onCheckedChanged(CompoundButton cb,
boolean isChecked) {
//do something here ...
}
});
答案 1 :(得分:1)
单击保存按钮时可以检索状态
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i=0; i<25; i++) {
CheckBox cb = (CheckBox) DynamicActivity.this.findViewById(i+10);
boolean isChecked = cb.isChecked();
// save it here
}
}
});