问题:如何以编程方式突出显示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