I am new to android,I am trying to show a listview with CheckedTextView on screen with few elements already checked, But couldn't succeed, my listview is always unchecked Here is my code,
final ListView listView = (ListView) findViewById(R.id.BusRoutesList);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.routes_list_item, R.id.stop_checkedtextbox, routesSubList);
listView.setAdapter(arrayAdapter);
for (int i = 0; i < routesSubList.size(); i++) {
if (selectedRoutesList.contains(routesSubList.get(i))) {
//listView.setItemChecked(i,true); No Luck
View v = listView.getAdapter().getView(i, null, null);
CheckedTextView checkedTextView = (CheckedTextView) v.findViewById(R.id.stop_checkedtextbox);
checkedTextView.setChecked(true);//I get correct row to be checked but not shown on screen
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position,
long id) {
CheckedTextView checkedTextView = (CheckedTextView) view.findViewById(R.id.stop_checkedtextbox);
boolean checked = checkedTextView.isChecked();
// String str =
if (checked) {
checkedTextView.setChecked(false);
selectedRoutesList.remove(listView.getItemAtPosition(position).toString());
} else {
selectedRoutesList.add(listView.getItemAtPosition(position).toString());
checkedTextView.setChecked(true);
}
}
});
Please advice, I dont know if i am missing something
You have given the listView a custom layout, so it don't know how it should be looked when an item is checked. You can try with override the getView().
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.routes_list_item, R.id.stop_checkedtextbox, routesSubList){
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = getActivity().getLayoutInflater().inflate(R.layout.routes_list_item);
}
CheckedTextView checkedTextView = (CheckedTextView) convertView.findViewById(R.id.stop_checkedtextbox);
if(listView.isItemChecked(position)){
checkedTextView.setChecked(true);
}else{
checkedTextView.setChecked(false);
}
return convertView;
}
};
The code is not tested. Hope it help!