我想使用onLongClick管理listView中的列表。 我想选择多个项目并管理(当选择时)在工具栏中添加1 botton(删除)。 我尝试使用此代码:
public class FragmentFragment extends Fragment {
private ListView listView;
private List<Schede> list;
private SchedeAdapter adapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), SecondActivity.class);
startActivity(intent);
}
});
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object object= list.get(position);
Toast.makeText(getContext(), object.getName() + "Clicked", Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Object object = list.get(position);
view.setSelected(true);
return false;
}
});
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
return rootView;
}
public void remove(int position){
SharedPreferences pref = getActivity().getSharedPreferences("OBJECTS", Context.MODE_PRIVATE);
list.remove(position);
String listS = new Gson().toJson(list);
SharedPreferences.Editor edit = pref.edit();
edit.putString("OBJECTS", listS);
edit.apply();
adapter.notifyDataSetChanged();
}
public void refresh(){
SharedPreferences pref = getActivity().getSharedPreferences("OBJECTS", Context.MODE_PRIVATE);
String string = pref.getString("OBJECTS", null);
if (string != null){
Type type = new TypeToken<List<Object>>(){}.getType();
list = new Gson().fromJson(string, type);
adapter = new ObjectAdapter(getContext(), list);
listView.setAdapter(adapter);
}
}
@Override
public void onResume(){
super.onResume();
refresh();
}
}
...但不允许我选择多个项目(我为xml中的所选项目设置了不同的背景颜色)。 其余代码正常工作
答案 0 :(得分:0)
已解决:https://stackoverflow.com/a/12598337/6941150 在onCreate()中使用...
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
...
}