問題:如何以編程方式突出顯示ListView中的選項?如何以編程方式選擇ListView項目
背景:我已經看過大量的這類問題的線程,但似乎沒有工作。我在使用自定義適配器從數據庫創建的列表填充的片段中有一個列表視圖。當片段被打開時,我希望默認選擇其中一個項目(取決於編輯模式是1 /啓用),我已準備好此項目的位置。我目前使用clientList.setChoiceMode(ListView.CHOICE_MODE_SINGLE)
,並嘗試用setItemChecked
突出顯示該選項,但它不起作用。
片段的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>
如果更多的代碼需要我很樂意提供。
這個問題是與我相似,不過答案給了我一個InflateException。
在此先感謝您的幫助。
是的方法被稱爲我通過登錄到該循環/ if語句內的控制檯進行檢查。即使只是在'onViewCreate'中放置'setItemChecked'也不會執行任何操作。 – Jack