我是android的新手,我将sample用于listview。因此,我无法更改代码。我的Listview的每个项目都有一个切换按钮。当我滚动Listview开关时,随机更改状态。如何使开关状态稳定?
我的listview类适配器:
public class MyCustomCursorAdapter extends CursorAdapter {
LIGHTS calling_activity;
private DatabaseHelper dbHelper;
public MyCustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
this.calling_activity = (LIGHTS) context;
}
@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, 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)));
ImageView option = view.findViewById(R.id.itemoption);
Switch thisswitch = view.findViewById(R.id.onoff);
thisswitch.setTag(cursor.getString(cursor.getColumnIndex(dbHelper._ID)));
thisswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { calling_activity.myOnCheckedChangedHandler((String)buttonView.getTag(),isChecked);
}
});
option.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView itemID = (TextView) view.findViewById(R.id.id);
TextView itemTitle = (TextView) view.findViewById(R.id.KEYCODE);
TextView itemDesc = (TextView) view.findViewById(R.id.NAME);
String myId = itemID.getText().toString();
String myTitle = itemTitle.getText().toString();
String myDesc = itemDesc.getText().toString();
Intent intent = new Intent(calling_activity, ModifyActivity.class);
intent.putExtra("Id", myId);
intent.putExtra("Title", myTitle);
intent.putExtra("Desc", myDesc);
calling_activity.startActivity(intent);
}
});
}
}
以及在我的Lights活动中:
@Override
public void myOnCheckedChangedHandler(String id, boolean check_status) {
Toast.makeText(
this,
"You changed the status for the row with an id of " + id +
" the status is now " + new Boolean(check_status).toString(),
Toast.LENGTH_SHORT).show();
String name = cursor.getString(cursor.getColumnIndex(dbHelper.DESC));
if(new Boolean(check_status).toString().equals("true")){
Toast.makeText(this,name +" is ON", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:1)
请在适配器的bindView内部通过if / else情况进行管理,您需要检查如下切换条件:
// set the code into bind
if(switchCondition1 == 1)
{
//set the code as per condition wise
}else{
//
}
更改状态后,您还需要将状态更改为列表项,并使用notifydatasetChanged()方法刷新列表项。