0
片段類:安卓:onItemCheckedStateChanged只調用一次
public class MultiFragmentListContent extends ListFragment
{
ListView listView;
ActionMode actionMode;
ArrayAdapter<String> arrayAdapter;
List<String> stringList;
Set<String> checkList;
AbsListView.MultiChoiceModeListener choiceModeListener = null;
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater,container,savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
checkList = new HashSet<>();
stringList = new LinkedList<>();
stringList.add("A");
stringList.add("B");
stringList.add("C");
stringList.add("D");
stringList.add("E");
listView = getListView();
arrayAdapter = new ArrayAdapter<String>(getActivity(),R.layout.string,stringList);
listView.setAdapter(arrayAdapter);
choiceModeListener = new AbsListView.MultiChoiceModeListener()
{
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked)
{
if(checked)
checkList.add(stringList.get(position));
else
checkList.remove(stringList.get(position));
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu)
{
actionMode = mode;
MenuInflater menuInflater = mode.getMenuInflater();
menuInflater.inflate(R.menu.contentmenu2,menu);
arrayAdapter = new ArrayAdapter<String>(getActivity(),R.layout.checkbox,stringList);
listView.setAdapter(arrayAdapter);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item)
{
switch(item.getItemId())
{
case R.id.contextmenu2:
for(String k : checkList)
{
stringList.remove(k);
Log.i(k,k);
}
actionMode.finish();
break;
}
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode)
{
arrayAdapter = new ArrayAdapter<String>(getActivity(),R.layout.string,stringList);
listView.setAdapter(arrayAdapter);
checkList.removeAll(checkList);
}
};
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(choiceModeListener);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
listView.setMultiChoiceModeListener(choiceModeListener);
return true;
}
});
}
}
我注意到,方法onItemCheckedStateChanged
只調用一次。
在該方法奏效之前,我的意思是它總是被調用。
我試圖在網上找到,但沒有找到解決方案。
我覺得現在的問題是
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
,但我不知道在哪裏把它。如果我把它放在其他地方,應用程序崩潰。
您可以在setChoiceMode()之後添加adapter.notifyDataSetChanged()並嘗試。 – Paul
@Paul它不起作用 – Curio
我已經嘗試了你的代碼,但它工作正常。在選擇模式下,函數onItemCheckedStateChanged()總是被調用。我仍然不知道問題出在哪裏。如果您在選擇模式中沒有選擇任何選項,它將退出選擇模式。你總是選擇同一件物品嗎? – Paul