Question: How do I highlight an option in a ListView programmatically?
Background: I have looked at tons of threads for this kind of issue however none seem to work. I have a list view in a fragment that is populated by a list created from a database using a custom adapter. When the fragment is opened I would like one of the items to be selected by default (depending on whether edit mode is 1/enabled), I have the position of this item ready. I currently use the clientList.setChoiceMode(ListView.CHOICE_MODE_SINGLE)
, and try to highlight the option with setItemChecked
but it doesn't work.
Fragment OnCreate
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
FragmentActivity faActivity = (FragmentActivity) super.getActivity();
final LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.fragment__client, container, false);
addJob = (AddJob)getActivity();
clientList = (ListView) linearLayout.findViewById(R.id.listView);
clientList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
dbHandler = new DraycottDataHandler(super.getActivity().getApplicationContext());
if (dbHandler.getClientCount() != 0)
Clients.addAll(dbHandler.getAllClients()); //Loads clients into Client list
populateList(); //Sets adapter for the listview.
if(addJob.getEdit() == 1) { //Get edit mode from activity
NewJobClass editJob = addJob.getEditJob();
for (int i = 0; i < Clients.size(); i++) {
ClientClass client = Clients.get(i);
if (client.getID() == editJob.getClientID()) {
clientList.setItemChecked(i, true); //Highlight item (doesnt do anything).
}
}
}
clientList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedClient = Clients.get(position);
listener.getClientData(selectedClient);
}
});
return linearLayout;
}
ListView XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.simple.jack.application.Fragment_Client">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"
android:choiceMode="singleChoice"
android:listSelector="#D3D3D3"
android:clickable="true"/>
</LinearLayout>
If more code is needed I'd be glad to provide it.
This question is similar to mine however the answer gives me an InflateException.
Thanks in advance for any help.