我有一个GridView实现并激活了
mGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
模式.现在,当我对一个项目执行长按时,我可以从网格中选择多个项目.我希望通过正常的短按实现此行为.这可能吗?
首先,我建议考虑这个用户场景是否是你一直在寻找的.默认情况下,在Android UX中选择您长按的内容,这是用户习惯的模式.所以,也许你应该重新考虑整个流程.
说,你真的需要GridView.CHOICE_MODE_MULTIPLE_MODAL
吗?
您可以在适配器级别处理它,只需存储选定的位置并在onClick
处理程序中更新此列表:
static final String[] numbers = new String[] { "A", "B", "C", "D", "E",.... "U", "V", "W", "X", "Y", "Z"}; ..... gridView = (GridView) findViewById(R.id.gridView1); final CustomAdapter adapter = new CustomAdapter(numbers); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView> parent, View v, int position, long id) { int selectedIndex = adapter.selectedPositions.indexOf(position); if (selectedIndex > -1) { adapter.selectedPositions.remove(selectedIndex); ((CustomView)v).display(false); } else { adapter.selectedPositions.add(position); ((CustomView)v).display(true); } } });
自定义BaseAdapter
显示自定义视图:
public class CustomAdapter extends BaseAdapter { private String[] strings; ListselectedPositions = new ArrayList<>(); CustomAdapter(String [] strings) { this.strings = strings; } @Override public int getCount() { return strings.length; } @Override public Object getItem(int position) { return strings[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { CustomView customView = (convertView == null) ? new CustomView(MainActivity.this) : (CustomView) convertView; customView.display(strings[position], selectedPositions.contains(position)); return customView; } }
自定义视图(在我的情况下 - 使用TextView的单元格).XML:
码:
class CustomView extends FrameLayout { TextView textView; public CustomView(Context context) { super(context); LayoutInflater.from(context).inflate(R.layout.custom_view, this); textView = (TextView)getRootView().findViewById(R.id.textView); } public void display(String text, boolean isSelected) { textView.setText(text); display(isSelected); } public void display(boolean isSelected) { textView.setBackgroundColor(isSelected? Color.RED : Color.LTGRAY); } }