Zohaib Siddique Zohaib Siddique - 1 month ago 17
Android Question

Set first Item checked of listview using ListFragment

I want to set first item checked of listview as default whenever an activity created. My activity consist of ListFragment which has ListView. The first item needs to be checked. I've write

listView.setItemChecked(0, true);
listView.setSelection(0);
listView.setSelected(true);


above code for check but on activity created it not get checked. kindly tell why and how i can achieve?

Full code:

public class LeftFilterContents extends ListFragment implements AdapterView.OnItemClickListener {

Get get;
View view;
ListView listView;

public interface Get {
void getData(int s);
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
get = (Get) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.list_fragment, container, false);
return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> arrayList = new ArrayList<>();
listView = (ListView) view.findViewById(android.R.id.list);

arrayList.add("Type");
arrayList.add("Date");
arrayList.add("From to Date");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, arrayList);
setListAdapter(adapter);
listView.setItemChecked(0, true);
listView.setSelection(0);
listView.setSelected(true);
getListView().setOnItemClickListener(this);

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
get.getData(position);
}


ListView:

<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>

Answer

Add this line :

adapter.notifyDataSetChanged();
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

So you will have :

ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),     android.R.layout.simple_list_item_1, arrayList);
setListAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);  
listView.setItemChecked(0, true);
getListView().setOnItemClickListener(this);
adapter.notifyDataSetChanged();
Comments