【发布时间】:2016-11-05 17:19:11
【问题描述】:
我有一个 listView,每行中有两个项目,一个 TextView 和一个 Switch 按钮。
这就是我创建列表视图的方式:
rootView = inflater.inflate(R.layout.fragment_list_view, container,false);
ListView list = (ListView) rootView.findViewById(R.id.listViewFragment);
rootView.findViewById(R.id.buttonSubmitPlayersTrainingAttendances) ;
String[] from = { "namePlayer", "switch" };
int[] to = { R.id.textViewPlayerName, R.id.switchAttendance };
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int a=0; a < totalPlayers ;a++)
{
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("namePlayer", playersSurnames.get(a) + " " + playersNames.get(a) );
aList.add(hm);
}
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.player_list, from, to);
list.setAdapter(adapter);
我使用了具有 listView 的布局 fragment_list_view.xml,然后在 SimpleAdapter 中我使用了 List> (aList) 和具有 TextView 和 Switch 的布局 player_list.xml。我不知道这是否是正确的方法,但它确实有效。
fragment_list_view.xml
<ListView
android:id="@+id/listViewFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
player_list.xml
<TextView
android:id="@+id/textViewPlayerName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<Switch
android:id="@+id/switchAttendance"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
如您所见,ListView 有效,我在屏幕上看到了我想要的内容:玩家列表和每个玩家的开关:
截图 --> Image
现在,如果我从适配器执行 getItem(),我会看到该行的第一个元素(Player1、Player2、...)
我的问题是:如何获取每行(每个玩家)的 Switch Id 以查看它是否被选中?如果我以错误的方式执行 ListView,你能解释一下最好的方法是什么吗? 谢谢
【问题讨论】:
-
您需要为每个玩家创建一个对象,而不是复杂的嵌套哈希图,在这个对象中,您将在适配器中使用 List 填充列表并根据
boolean status决定它是开还是关,当你getItem()它将返回一个player你可以检查Player#getStatus()以查找是开还是关,以及何时开关单击您需要根据切换按钮状态将该玩家(对象)列表更新为setStatus()。 -
是的,我使用了一个自定义的 SimpleAdapter 而不是 HashMap,它运行良好,谢谢!