Firstly
I can not see a call for notifydatasetChange()
that will refresh the ListView. So in onClick()
after changing backing datasource, you should refresh the adapter too.
Alternative
In getView() you can set onClickListener
for checkBox
and for every onClick()
callback you should update backing datasource and call `toggle() on checkbox to toggle the state.
Code
Model class class Model {
public Model(String data, boolean state) {
this.data = data;
this.state = state;
}
String data;
Boolean state;
// getter and setters
}
Custom Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.single_row, null, false);
TextView tv = (TextView) view.findViewById(R.id.content);
CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.checker);
Model m = backingsource.get(position);
tv.setText(m.getData());
ctv.setChecked(m.getState());
return view;
}
Activity
public class MainActivity extends Activity implements OnClickListener {
CustomAdapter mAdapter = null;
List<Model> mDataSource = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDataSource = new ArrayList<Model>();
mDataSource.add(new Model("Tom", false));
mDataSource.add(new Model("Goffy", false));
mDataSource.add(new Model("Ron", false));
mDataSource.add(new Model("Pit", false));
mDataSource.add(new Model("Dwyane", false));
mDataSource.add(new Model("John", false));
mDataSource.add(new Model("Son", false));
mAdapter = new CustomAdapter(this, mDataSource);
}
@Override
protected void onResume() {
super.onResume();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setSingleChoiceItems(mAdapter, -1, this);
builder.setTitle("Customized");
builder.create().show();
}
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("@gaurav", "which " + which);
Model m = mDataSource.get(which);
boolean b = m.getState();
b = !b;
m.setState(b);
mAdapter.notifyDataSetChanged();
}
}
single_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Some text" >
</TextView>
<CheckedTextView
android:id="@+id/checker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checkMark="?android:attr/listChoiceIndicatorSingle" />
</LinearLayout>