我是android新手。我有一个带有一个开关按钮的列表视图。当我向下滚动时。自第13项起,listview似乎就和第一项一样。例如,当我启用第一项的开关时,第十三项的开关也处于启用状态。(数字取决于滚动前要在屏幕上显示多少项)
Mainactivity.java:
@Override
public void myOnCheckedChangedHandler(String id, boolean check_status) {
String rowid = cursor.getString(cursor.getColumnIndex(dbHelper._ID));
String key = cursor.getString(cursor.getColumnIndex(dbHelper.TITLE));
String name = cursor.getString(cursor.getColumnIndex(dbHelper.DESC));
String state = cursor.getString(cursor.getColumnIndex(dbHelper.Switchstate));
if(new Boolean(check_status).toString().equals("false")){
state="off";
dbManager.update(Integer.parseInt(rowid), key, name, state);
Toast.makeText(this,name +" is "+ state, Toast.LENGTH_SHORT).show();
}
if(new Boolean(check_status).toString().equals("true")){
state = "on";
dbManager.update(Integer.parseInt(rowid), key, name, state);
Toast.makeText(this,name +" is "+ state, Toast.LENGTH_SHORT).show();
}
refresh();
}
public void refresh(){
cursor = dbManager.fetch();
adapter = new MyCustomCursorAdapter(this, cursor);
users_list.setAdapter(adapter);
}]
listviewadapter.java:
public class MyCustomCursorAdapter extends CursorAdapter {
Mainactivity calling_activity;
private DatabaseHelper dbHelper;
public MyCustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
this.calling_activity = (LIGHTS) context; //<<<<<<<<<<@@@@@@@@@@@ ADDED for interface
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
return view;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.adapter,parent,false);
}
@Override
public void bindView(final View view, Context context, final Cursor cursor) {
((TextView)view.findViewById(R.id.id)).setText(cursor.getString(cursor.getColumnIndex(dbHelper._ID)));
((TextView)view.findViewById(R.id.KEYCODE)).setText(cursor.getString(cursor.getColumnIndex(dbHelper.TITLE)));
((TextView)view.findViewById(R.id.NAME)).setText(cursor.getString(cursor.getColumnIndex(dbHelper.DESC)));
((TextView)view.findViewById(R.id.lightstate)).setText(cursor.getString(cursor.getColumnIndex(dbHelper.Switchstate)));
ImageView option = view.findViewById(R.id.itemoption);
Switch thisswitch = view.findViewById(R.id.onoff);
thisswitch.setTag(cursor.getString(cursor.getColumnIndex(dbHelper.Switchstate)));
if(cursor.getString(cursor.getColumnIndex(dbHelper.Switchstate)).equals("on")){
thisswitch.setChecked(true);
}
if(cursor.getString(cursor.getColumnIndex(dbHelper.Switchstate)).equals("off")){
thisswitch.setChecked(false);
}
thisswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { calling_activity.myOnCheckedChangedHandler((String)buttonView.getTag(),isChecked);
}
});
}}